取a与b的最大值

来源:互联网 发布:知达常青藤中学校电话 编辑:程序博客网 时间:2024/06/04 20:01

题目:There are two int variables : a and b , don't use " if " , " ?: " , " switch " or other judgement statements , find out the biggest one of the two numbers.(有两个变量a和b,不用 " if " , " ?: " , " switch "或其他判断语句,找出两个数中的较大值)程序员面试宝典第三版P40

方案一:

 

int max = ((a+b)+abs(a-b))/2;


方案二:

#include <iostream>using namespace std;int greater(int a ,int b);int main(){int a = 11;int b = 32;cout << greater(a,b) << endl;return 0;}int greater(int a ,int b){int flag;flag = (a-b) >> (sizeof(int) * 8 -1); //得到符号位即最高位 0 或 1;return -flag * b + (1 + flag) *a ;}


 


 

0 0
原创粉丝点击