剑指奥否位运算
很喜欢评论区的一条评论:“我是xx”
首先回顾一下数电的基础
计算机中存储数值,都是以二进制补码的形式存入的,正数的补码是他本身,负数的补码是反码加一。
回顾下Python的位运算符
print(hex(1)) # = 0x1 补码
print(hex(-1)) # = -0x1 负号 + 原码 ( Python 特色,Java 会直接输出补码)
print(hex(1 & 0xffffffff)) # = 0x1 正数补码
print(hex(-1 & 0xffffffff)) # = 0xffffffff 负数补码
print(-1 & 0xffffffff) # = 4294967295 ( Python 将其认为正数)
作者:jyd
链接:https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/solution/mian-shi-ti-65-bu-yong-jia-jian-cheng-chu-zuo-ji-7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def add(self, a: int, b: int) -> int:
x=0xffffffff#计算补码
a=x&a
b=b&x
while b!=0:
c=(a&b)<< 1 &x
a=(a^b)
b=c
return a if a <= 0x7fffffff else ~(a ^ x)