您的位置:首页 > 其它

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

2009-04-30 16:13 399 查看
许多朋友说,要考虑溢出问题,我想这个应该很简单吧

我们还有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

这样的结果才是最需要的!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: