如何求两个int型的最大值,感觉很不错!

这是在论坛里看到的一精华贴,自己将代码总结下来,做为一个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<b在java里为boolean不能自动转换为int类型。所以编译器不能通过。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT人.阿标

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值