Moderate 不用比较符返回较大的数 @CareerCup

通过判断a-b的最高位来知道哪一个数比较大

但是要注意overflow的情况

if a and b have different signs:
	//  if a > 0, then b <  <d,  and  k = l.
	// if a < 0, then b > 0, and k = 0.
	// so either way, k = sign(a)
	let k = sign(a)
else
	let  k  = sign(a  -  b)  //  overflow  is  impossible

但因为不能用if else所以用乘法来代替: 
int k = use_sign_of_a * sa + use_sign_of_c * sc;


package Moderate;


/**
 * Write a method which finds the maximum of two numbers. You should not use if-else or any other comparison operator.

EXAMPLE

Input: 5, 10

Output: 10

译文:

写一个函数返回两个数中的较大者,你不能使用if-else及任何比较操作符。 
 *
 */
public class S17_4 {

	/* Flips a 1 to a 0 and a 0 to a 1 */
    public static int flip(int bit) {
            return 1 ^ bit;
    }
    
    /* Returns 1 if a is positive, and 0 if a is negative */
    public static int sign(int a) {
            return flip((a >> 31) & 0x1);
    }
    
    public static int getMaxNaive(int a, int b) {
            int k = sign(a - b);
            int q = flip(k);
            return a * k + b * q;
    }
    
    public static int getMax(int a, int b) {
            int c = a - b;
            
            int sa = sign(a); 		// if a >= 0, then 1 else 0
            int sb = sign(b); 		// if b >= 0, then 1 else 0
            int sc = sign(c);		// depends on whether or not a - b overflows
            
            /* We want to define a value k which is 1 if a > b and 0 if a < b. 
             * (if a = b, it doesn't matter what value k is) */
            
            int use_sign_of_a = sa ^ sb; 		// If a and b have different signs, then k = sign(a)
            int use_sign_of_c = flip(sa ^ sb); 	// If a and b have the same sign, then k = sign(a - b)
            
            /* We can't use a comparison operator, but we can multiply values by 1 or 0 */
            int k = use_sign_of_a * sa + use_sign_of_c * sc;
            int q = flip(k); // opposite of k
            
            return a * k + b * q;
    }
    
    public static void main(String[] args) {
            int a = 26;
            int b = -15;
            
            System.out.println("max_naive(" + a + ", " + b + ") = " + getMaxNaive(a, b));
            System.out.println("max(" + a + ", " + b + ") = " + getMax(a, b));                
            
            a = -15;
            b = 2147483647;
            
            System.out.println("max_naive(" + a + ", " + b + ") = " + getMaxNaive(a, b));
            System.out.println("max(" + a + ", " + b + ") = " + getMax(a, b));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值