如何不使用比较和判断查找最大值
2013-11-22 17:12
225 查看
给定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值如何取得。
reference:
Cracking the coding interview
这里可以学习几个有趣的函数:
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
相关文章推荐
- 如何使用PowerShell查找占用磁盘空间最大的文件
- 不使用if、?:、switch及其他判断语句如何找出两个int型变量中的最大值和最小值
- 如何使用C++递归来实现查找BST(Binary Search Tree)的最大高度
- 设计一个最优算法来查找一n个元素数组中的最大值和最小值。已知一种需要比较2n次的方法,请给一个更优的算法。
- 如何使用jquery选择多个checkbox以及如何判断checkbox选中的数量
- 使用FileSystemWatcher监测大文件时,如何判断文件已经创建完成?
- 如何判断自己的机器是使用什么存储模式
- 如何查找Authorization object在哪些ABAP代码里使用到
- SQL查询如何判断要查找的字符是否在一个指定集合中
- 线性查找法————使用查找键逐个与数组元素进行比较实现查找
- 如何使用SPY++查找
- linux shell 编程1文件权限检测、字符串比较判断、数值大小比较、时间获取以及单引号双引号反引号等的使用
- 【C++基本功补习】查找三个数据中的最大值、最小值、中间值,两种实现方案比较
- 查找资料, 学习如何使用命令安装gcc/g++, gdb, vim
- 如何使用程序判断系统是大端还是小端?
- Sql Server2005中获取表中某一列的最大值使用MAX和TOP-ORDER BY执行效率比较
- destoon 的登录过程,如何使用cookie来判断用户是否登录
- [PHP]如何使用Mobile_Detect来判断访问网站的设备:安卓,平板,电脑
- S60 3rd下如何使用HookLogger查找内存泄漏错误?