def bin32(a):
mask = 0xFFFFFFFF
a &= mask
res = ''
i = 0
while a != 0 or i < 32:
res = str(a & 1) + res
a >>= 1
i += 1
print(res)
def bin64(a):
mask = 0xFFFFFFFFFFFFFFFF
a &= mask
res = ''
i = 0
while a != 0 or i < 64:
res = str(a & 1) + res
a >>= 1
i += 1
print(res)
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
# 32 bits integer max
MAX = 0x7FFFFFFF
# 32 bits interger min
MIN = 0x80000000
# mask to get last 32 bits
mask = 0xFFFFFFFF
bin32(a)
bin32(b)
while b != 0:
# ^ get different bits and & gets double 1s, << moves carry
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
bin32(a)
bin64(a)
bin64(~(a ^ mask))
return a if a <= MAX else ~(a ^ mask)
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
# 32 bits integer max
MAX = 0x7FFFFFFF
# mask to get last 32 bits
mask = 0xFFFFFFFF
while b != 0:
# ^ get different bits and & gets double 1s, << moves carry
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
return a if a <= MAX else ~(a ^ mask)
# a > MAX, 就是 32bits的最高位为1,python会把这个数处理成正数,但是我们应该把它做为负数处理
# ~(a ^ mask)的目标就是把
# 0000000000000000000000000000000011111111111111111111111111101100 变成
# 1111111111111111111111111111111111111111111111111111111111101100
# res = Solution().getSum(1, 2)
# print(res)
#
# res = Solution().getSum(20, 30)
# print(res)
#
# res = Solution().getSum(-1, 1)
# print(res)
res = Solution().getSum(-12, -8)
print(res)
# bin32(2)
# bin32(~2)
# bin32(~2+1)
# bin32(-2) # -2 = ~2 + 1
#
# bin32(1)
# bin32(-1)
LC-371 Sum of Two Integers
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- My SubmissionsDifficulty: EasyContributors: Admin Calcula...
- Calculate the sum of two integers a and b, but you are no...
- Calculate the sum of two integers a and b, but you are no...
- 题目描述:Calculate the sum of two integers a and b, but you a...