不用比较运算符,判断int型的a,b两数的大小 考虑溢出问题

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

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

许多朋友说,要考虑溢出问题,我想这个应该很简单吧


我们还有long 这个类型啊!

  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

这里写图片描述

猜你喜欢

转载自blog.csdn.net/jgfyyfd/article/details/84076995