给定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