这是在论坛里看到的一精华贴,自己将代码总结下来,做为一个java文件,备后面的复习:
/**
* 两个整型数,不准用if 、switch 、?:等判断语句求出两者最大值。
* 不能使用api
*/
public class Print_Max {
public static void main(String[] args) {
int[] a = { 11, 21 };
System.out.print("Method One:");
System.out.println(max(a));
int x = 11;
int y = 21;
System.out.print("Method Two:");
System.out.println(max(x, y));
System.out.print("Method Two2:");
System.out.println(max2(x,y));
System.out.print("Method Three:");
System.out.println(maxAbs(x, y));
}
// 这种方法y=x的时候,就不对了。
private static int max(int x, int y) {
return y * ((x - y) >>> 31) + x * ((y - x) >>> 31);
}
// 如果上面的方法改成这样就不会有问题了;
private static int max2(int x, int y) {
return x * (1 - ((x - y) >>> 31)) + y * ((x - y) >>> 31);
}
public static int max(int a[]) {
return a[((a[0] - a[1]) >> 31) & 1];//
}
public static int maxAbs(int x,int y){
return (x+y+Math.abs(x-y))/2;
}
}输出结果:
Method One:21
Method Two:21
Method Two2:21
Method Three21
看了论坛的这些回答感觉真的很了不起,开始我看到这个帖的时候,根本无从下手,但是看了之后,感觉 都能看懂,而且知识点都是以前老师都讲过的,真是很惭愧,目前还不能独立去思考问题啊,看来要多多学习学习,多多思考。
还有这个代码:
int max4(int a, int b)
{
int ret[2] = {a, b};
return ret[a < b];
}这个代码开始看似乎很不错,感觉也是正确 的,但是运行之后 有错,才知道a