不用比较运算符,判断int型的a,b两数的大小,考虑溢出问题
2009-04-30 16:13
399 查看
许多朋友说,要考虑溢出问题,我想这个应该很简单吧
我们还有long 这个类型啊!
现在的问题是,如何把>= 分开,也就是大于返回1, 等于返回0, 小于返回-1
这样的结果才是最需要的!
我们还有long 这个类型啊!
/** * 不用比较运算符,判断int型的a,b两数的大小,考虑溢出问题. * * @author J***A世纪网(java2000.net, laozizhu.com) */ public class Test { private static final String[] buf = { "a>=b", "a < b" }; public static void main(String[] args) { System.out.println(compare(1, 2)); // 1 < System.out.println(compare(2, 2)); // 0 >= System.out.println(compare(2, 1)); // 0 >= System.out.println(compare(Integer.MIN_VALUE, Integer.MAX_VALUE)); // 1 < System.out.println(compare(Integer.MAX_VALUE, Integer.MIN_VALUE)); // 0 >= } /** * 比较2个整数(int)的大小。 * * @param a * @param b * @return */ public static int compare(int a, int b) { return (int) (((long) a - (long) b) >>> 63); } }
现在的问题是,如何把>= 分开,也就是大于返回1, 等于返回0, 小于返回-1
这样的结果才是最需要的!
相关文章推荐
- 不用比较运算符,判断int型的a,b两数的大小,考虑溢出问题
- 不用比较运算符,判断int型的a,b两数的大小
- 不用比较运算符,判断int型的a,b两数的大小的答案
- 不用比较运算符,判断int型的a,b两数的大小的答案
- 不用比较运算符及循环控制语句,判断int型的a、b两数的大小
- 不用比较运算符,判断int型的a,b两数的大小
- 不用比较运算符,判断int型的a,b两数的大小的答案
- 不用比较运算符及循环控制语句,判断int型的a、b两数的大小
- 不用比较运算符,判断int型的a,b两数的大小。
- 不用比较运算符及循环控制语句,判断int型的a、b两数的大小
- 不用比较运算符及循环控制语句,判断int型的a、b两数的大小
- 一个比较有意思的判断两数大小的方法,不用逻辑比较运算符
- 用Groovy实现判断两个int数值大小(不用比较运算符,考虑溢出)
- 一个比较有意思的判断两数大小的方法,不用逻辑比较运算符
- 不用比较运算符判断数的大小
- 交换两数,不使用第三变量,且考虑溢出问题
- 交换两数,不使用第三变量,且考虑溢出问题
- 交换两数,不使用第三变量,且考虑溢出问题
- 不用比较符判断两个数的大小 (移位)
- C++ 不用判断运算符进行比较两个数的大小