371. Sum of Two Integers [easy] (Python)

来源:互联网 发布:淘宝拍卖房产过户 编辑:程序博客网 时间:2024/06/16 00:55

题目链接

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

0 1