Description

对于两个32位整数a和b,请设计一个算法返回a和b中较大的。但是不能用任何比较判断。若两数相同,返回任意一个。

给定两个整数ab,请返回较大的数。

测试样例:

1,2
返回:2

Solutions

1. Bit Manipulation

# -*- coding:utf-8 -*-

class Compare:
    def getMax(self, a, b):
        c = a - b
        a_s = self.get_sign(a)
        b_s = self.get_sign(b)
        c_s = self.get_sign(c)
        # if signs of a and b are same or not, same get 0, not same get 1
        diff_ab = a_s ^ b_s
        same_ab = self.flip(diff_ab) # same get 1, not same get 0
        # a,b如果符号相同,取差值c的符号,如果a,b符号不同,直接取a的符号
        return_a = diff_ab * a_s + same_ab * c_s
        return_b = self.flip(return_a)
        return return_a * a + return_b * b
    
    def flip(self, n):
        return 1 ^ n
    
    def get_sign(self, n):
        return self.flip((n >> 31) & 1)

References

  1. 8.5 比较两数