面试题:两个整数不使用比较运算符和API得到更大的那个值

来源:互联网 发布:linux激活网卡命令 编辑:程序博客网 时间:2024/06/02 11:59

两个整型数,不准用if 、switch 、?:等判断语句求出两者大值,不能使用api

我这里2个实现方法如下:

view plaincopy to clipboardprint?
/** 
 * 不用比较运算符得到2个数字的更大值。 
 *  
 * @author JAVA世纪网(java2000.net) 
 */ 
public class Test3 {  
  public static void main(String[] args) {  
    int[] as = { 44, 55, 44, 4, 40, -44, -55 };  
    int[] bs = { 55, 44, 4, 44, 40, -55, -44 };  
    for (int i = 0; i < as.length; i++) {  
      System.out.println(max2(as[i], bs[i]));  
      System.out.println(max3(as[i], bs[i]));  
      System.out.println();  
    }  
  }  
  /** 
   * 使用移位操作 
   *  
   * @param a 
   * @param b 
   * @return 
   */ 
  public static int max2(int a, int b) {  
    int[] nums = { a, b };  
    return nums[(a - b) >>> 31];  
  }  
  /** 
   * 使用乘法操作 
   *  
   * @param a 
   * @param b 
   * @return 
   */ 
  public static int max3(int x, int y) {  
    return x-(x-y)*((x-y)>>>31);  
  }  

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/java2000_net/archive/2009/08/24/4477755.aspx

原创粉丝点击