題目連結
https://leetcode.com/problems/sum-of-two-integers/ 題目原文
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3. 題目翻譯
計算兩個整數a和b的和,但是不能使用運算子加號和減號。
比如:給定a=1,b=2,返回3。 思路方法
既然不能使用加法和減法,那麼就用位操作。下面以計算5+4的例子說明如何用位操作實現加法:
1. 用二進位表示兩個加數,a=5=0101,b=4=0100;
2. 用and(&)操作得到所有位上的進位carry=0100;
3. 用xor(^)操作找到a和b不同的位,賦值給a,a=0001;
4. 將進位carry左移一位,賦值給b,b=1000;
5. 迴圈直到進位carry為0,此時得到a=1001,即最後的sum。
上面思路還算正常,然而對於Python就有點麻煩了。因為Python的整數不是固定的32位,所以需要做一些特殊的處理,具體見代碼吧。
代碼裡的將一個數對0x100000000模數(注意:Python的模數運算結果恒為非負數),是希望該數的二進位表示從第32位開始到更高的位都同是0(最低位是第0位),以在0-31位上類比一個32位的int。 思路一
迭代求解。
代碼
class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ while b != 0: carry = a & b a = (a ^ b) % 0x100000000 b = (carry << 1) % 0x100000000 return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)
思路二
遞迴求解。
代碼
class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ tmp_a = self.add(a, b) return tmp_a if tmp_a <= 0x7FFFFFFF else tmp_a | (~0x100000000+1) def add(self, a, b): return a if b == 0 else self.add((a ^ b) % 0x100000000, ((a & b) << 1) % 0x100000000)
PS: 新手刷LeetCode,新手寫部落格,寫錯了或者寫的不清楚還請幫忙指出,謝謝。
轉載請註明:http://blog.csdn.net/coder_orz/article/details/52034541