首页 > 代码库 > 《Cracking the Coding Interview》——第17章:普通题——题目4
《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\n", mymax(x, y)); 18 } 19 20 return 0; 21 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。