《Cracking the Coding Interview》——第17章:普通题——题目4

2014-04-28 22:32

题目:不用if语句或者比较运算符的情况下,实现max函数,返回两个数中更大的一个。

解法:每当碰见这种无聊的“不用XXX,给我XXX”型的题目,我都默认处理的是int类型。最高位是符号位,用x - y的符号位来判断谁大谁小。请看下面代码,条件表达式配合异或运算能满足题目的要求。

代码:

 1 // 17.4 Find the maximum of two numbers without using comparison operator or if-else statement.
 2 // Use bit operation instead. But this solution applies to integer only.
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 int mymax(int x, int y)
 7 {
 8     static const unsigned mask = 0x80000000;
 9     return (x & mask) ^ (y & mask) ? ((x & mask) ? y : x) : ((x - y & mask) ? y : x);
10 }
11 
12 int main()
13 {
14     int x, y;
15     
16     while (scanf("%d%d", &x, &y) == 2) {
17         printf("%d
", mymax(x, y));
18     }
19     
20     return 0;
21 }
原文地址:https://www.cnblogs.com/zhuli19901106/p/3698141.html