不用比較運算子,判斷int型的a,b兩數的大小 考慮溢位問題
阿新 • • 發佈:2018-11-17
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
許多朋友說,要考慮溢位問題,我想這個應該很簡單吧
我們還有long 這個型別啊!
[java] view plain copy
- /**
- * 不用比較運算子,判斷int型的a,b兩數的大小,考慮溢位問題.
- *
- * @author JAVA世紀網(java2000.net, laozizhu.com)
- */
- public class Test {
- private
- 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
這樣的結果才是最需要的!