不用比较运算符,判断int型的a,b两数的大小。

来源:互联网 发布:python 列表转多层字典 编辑:程序博客网 时间:2024/04/30 08:35

       这是justinavril一道面试题:

 

  public class TestCompare {
  public static String compare(Integer x,Integer y){
  String [] buf={">"," <"};
  int result=(x-y)>>>31;
  System.out.println(result);
  return buf[result];
 }
  public static void main(String[] args){
    int i =2;
    int j =3;
    String aa = compare(i,j);
      System.out.println(aa);
  }
}

 

 这是测试代码,代码并非我原创的。

 用来学习学习下阿,呵,还有这么雷人的面试题阿。汗一个!

 位运算符
一共3个移位运算符,左移位<<,右移位>>和无符号移位>>>。左移位<<在低位处补0。右移位>>若值为正则在高位插入0,若值为负则在高位插入1。无符号右移位>>>无论正负都在高位处插入0。

  1010 0000 0000 0000 0000 0000 0000 0000 >>> 4
   gives 0000 1010 0000 0000 0000 0000 0000 0000