
正文
《Cracking the Coding Interview》——第17章:普通题——题目4
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
2014-04-28 22:32
题目:不用if语句或者比较运算符的情况下,实现max函数,返回两个数中更大的一个。
解法:每当碰见这种无聊的“不用XXX,给我XXX”型的题目,我都默认处理的是int类型。最高位是符号位,用x - y的符号位来判断谁大谁小。请看下面代码,条件表达式配合异或运算能满足题目的要求。
代码:
// 17.4 Find the maximum of two numbers without using comparison operator or if-else statement.
// Use bit operation instead. But this solution applies to integer only.
#include <cstdio>
using namespace std; int mymax(int x, int y)
{
static const unsigned mask = 0x80000000;
return (x & mask) ^ (y & mask) ? ((x & mask) ? y : x) : ((x - y & mask) ? y : x);
} int main()
{
int x, y; while (scanf("%d%d", &x, &y) == ) {
printf("%d\n", mymax(x, y));
} return ;
}





