1. 程式人生 > >不用比較運算子,判斷int型的a,b兩數的大小 考慮溢位問題

不用比較運算子,判斷int型的a,b兩數的大小 考慮溢位問題

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

許多朋友說,要考慮溢位問題,我想這個應該很簡單吧


我們還有long 這個型別啊!

[java] view plain copy
print ?
  1. /** 
  2.  * 不用比較運算子,判斷int型的a,b兩數的大小,考慮溢位問題. 
  3.  *  
  4.  * @author JAVA世紀網(java2000.net, laozizhu.com) 
  5.  */  
  6. public class Test {  
  7.   private 
    static final String[] buf = { "a>=b""a < b" };  
  8.   public static void main(String[] args) {  
  9.     System.out.println(compare(12)); // 1 <
      
  10.     System.out.println(compare(22)); // 0 >=  
  11.     System.out.println(compare(21)); // 0 >=  
  12.     System.out.println(compare(Integer.MIN_VALUE, Integer.MAX_VALUE)); // 1 <  
  13.     System.out.println(compare(Integer.MAX_VALUE, Integer.MIN_VALUE)); // 0 >=  
  14.   }  
  15.   /** 
  16.    * 比較2個整數(int)的大小。 
  17.    *  
  18.    * @param a 
  19.    * @param b 
  20.    * @return 
  21.    */  
  22.   public static int compare(int a, int b) {  
  23.     return (int) (((long) a - (long) b) >>> 63);  
  24.   }  
  25. }  
/** * 不用比較運算子,判斷int型的a,b兩數的大小,考慮溢位問題. *  * @author JAVA世紀網(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

這樣的結果才是最需要的!

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述