Monday, November 18, 2013

17.4 [CTCI]

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

Solution: Given two numbers a and b: one straightforward idea is to check the sign of a-b; if a-b>0, return a, otherwise b; but it is possible that a-b overflows if a and b have different signs. So we can not do this way. We need to consider two cases:
1. a and b have the same signs: return a if a-b>0, otherwise b;
2. a and b have different signs: return a if a>0, otherwise b;
We define k=1 iff (sign(a)=sign(b) && a-b>0)  OR (sign(a)!=sign(b)&&a>0) and p to be inverse of k, i.e., 1^k. Then, the maximum of a and b is a*k+b*p.
int sign(int a){
    return 1^(a>>31 && 1);
}
int getMax(int a, int b){
    int c = a-b;
    int sa = sign(a);
    int sb = sign(b);
    int sc = sign(c);
    
    int diff = sa ^ sb;
    int same = 1^diff;
    int k = sc*same + sa*diff;
    int p = 1^k;
    return a*k+b*p;
}

No comments:

Post a Comment