面试题】找出两个整数 a,b 中的较大者
记录一下吧
- 位运算
请写一个程序,不用 if,条件表达式,switch 等判断语句,找出两个整数 a,b 中的较大者。
我当时一直纠结什么a/b和1的大小,或者说和1/2的大小。但是可以用
位运算
class Solution:def find_larger(self, a, b):# 计算 a - b 的差值diff = a - b# 通过差值的符号来判断result = ['a large','b large'][(diff >> 31) & 1]# 输出结果print(result)# this is my code, where can it still be optimized?
lc = Solution()
# 测试
a = 5
b = 3
lc.find_larger(a, b) # 输出: a largea = 2
b = 8
lc.find_larger(a, b) # 输出: b large
目前就这种方法最合适吧,我也想不到别的