如何不使用比较和判断查找最大值

给定a和b两个整数如何不使用比较和判断操作来实现输出其最大值?

这里可以学习几个有趣的函数:

1 获取一个数的正或负符号

2 反转一个符号

这里是通过符号的判断来巧妙地实现的。

基本思路:

符号位正,用1表示,符号是负用0表示。

有四种情况:

1 a b同号, a正,b负,那么最大值肯定是a,只要a乘以自己的符号1,b乘以自己的符号0,得出的就是最大值

2 a b同号, 也一样道理

3 a b异号, k = a-b的符号,a*k+b*k如果a大,那么k为1,式子等于a,如果b大,那么k为0,式子等于b。返回a*k + b*k就是其最大值了

4 a b异号, 一样道理

为什么要分四种情况呢?因为要考虑a b异号的时候a-b有可能溢出,这里最巧妙的就是不通过判断实现这四种情况了。

这个直接看程序,然后跟着程序走几遍,应该就没问题了。

分四种情况走一走,看看下面程序中的k值如何取得。

#include<iostream>
#include<vector>

using namespace std;

int flipSign(int a)
{
	return a^1;
}

int getSign(int a)
{
	//we need &0x1, ortherwise we won't be able to flip minus.
	//if positive, return 1, minus, return 0
	return flipSign((a>>31)&0x1);
}

int maxWithComp(int a, int b)
{
	int c = a-b;
	int sa = getSign(a);
	int sb = getSign(b);
	int sc = getSign(c);

	//if a b are different sign, use_sign_of_a = 1; use_sign_of_c = 0; otherwise the other way around
	int use_sign_of_a = sa^sb;
	int use_sign_of_c = flipSign(sa^sb);

	//if a is positive, and a b are the same sign, use_sign_of_a is 0; k the same sign as sc
	//if a is positive, and a b are the different sign, k is positive, the same sign as a
	//if a is negative, and a b are the same sign, use_sign_of_a is 0; k the same sign as sc 
	//if a is negative, and a b are the defferent sign, k is negative, the same sign as a
	int k = use_sign_of_a * sa + use_sign_of_c * sc;
	int q = flipSign(k);

	return a*k + b*q;
}

int main() 
{
	cout<<maxWithComp(8,5)<<endl;
	cout<<maxWithComp(-8,5)<<endl;
	cout<<maxWithComp(2, 9)<<endl;
	cout<<maxWithComp(2,-9)<<endl;
	cout<<maxWithComp(-29, -200)<<endl;
	system("pause");
	return 0;
}


reference:

Cracking the coding interview

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值