Sum of Two Integers
要点:
- 基本原理就是a^b得到无进位和,a&b得到carry并左移继续计算,这个算法适用于negative因为signed integer都是2’s complement表示的,所以加法都是统一算法。
- 上述算法只适合java,python因为自动整数越界为long。用python要用0x10000000 (33位)做mask取模保持int。
错误点
- 开始最好把a作为res,b作为carry,所以loop条件是b>0
- a和b会变化,所以要把旧值先存下,这点python可以同时赋值
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX_INT = 0x7FFFFFFF
MIN_INT = 0x80000000
MASK = 0x100000000
while b:
a,b = (a^b) % MASK, ((a&b)<<1 % MASK)
return a if a<=MAX_INT else (a % MIN_INT)-MIN_INT
# # print bin(a),bin(b)
# res, carry = a ^ b, (a & b)<<1 # error 2: don't forget shift left
# while carry:
# r = res^carry
# #print bin(res), bin(carry)
# carry = (res & carry) << 1 # error 1: order: should be last res and last carry
# #print bin(res), bin(carry)
# res = r
# return res