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

來源:互聯網
上載者:User
題目連結

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.