算法--两个数大小比较,不用分支判断

来源:互联网 发布:东方赢家软件下载 编辑:程序博客网 时间:2024/06/07 00:26

说明:摘自《程序员面试宝典(第二版)》,以及同学讨论

 

原题:

There are two in 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”或其他判断语句,找出两个数中间比较大的)

 

方法一

&&其实也是一种分支判断,所以它应该不算答案

int max1(int a, int b){  int tmp = a;  (b > a) && (tmp = b);  return tmp;}

 
方法二

这个方法可能会产生溢出

int max2(int a, int b){  return (a + b + abs(a - b)) / 2;}

 
方法三

注意这里的unsigned类型转换

int max3(int a, int b){  int c = a-b;  int arr[] = {a, b};  return arr[unsigned(c) >> sizeof(int) * 8 - 1];}

 

原创粉丝点击