Sum of Two Integers 解題教學:3 種解法完整比較|LeetCode 371 Best Practice

Sum of Two Integers 解題教學示意圖|LeetCode 371

本文完整拆解 LeetCode 371 Sum of Two Integers 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Sum of Two Integers 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given two integers a and b, return the sum of the two integers without using the operators + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = 2, b = 3
Output: 5

Constraints:

  • -1000 <= a, b <= 1000

Python

				
					# time complexity: O(1)
# space complexity: O(1)
class Solution:
    def getSum(self, a: int, b: int) -> int:
        x, y = abs(a), abs(b)
        # ensure that abs(a) >= abs(b)
        if x < y:
            return self.getSum(b, a)

        # abs(a) >= abs(b) -->
        # a determines the sign
        sign = 1 if a > 0 else -1

        if a * b >= 0:
            # sum of two positive integers x + y
            # where x > y
            while y:
                answer = x ^ y
                carry = (x & y) << 1
                x, y = answer, carry
        else:
            # difference of two integers x - y
            # where x > y
            while y:
                answer = x ^ y
                borrow = ((~x) & y) << 1
                x, y = answer, borrow

        return x * sign


a = 1
b = 2
print(Solution().getSum(a, b))


velocities = [0, 0.5, 1, 1.5]
movement = velocities[1:3]

print(movement)
				
			

Sum of Two Integers 解題思路

不能用加減號,就得回到硬體層面思考:XOR 可以算出「不進位的和」,AND 再左移一位可以算出「進位」。把兩者反覆相加(同樣用這兩個運算)直到進位為 0,就是最終答案——這正是全加器的邏輯。

Sum of Two Integers 演算法步驟

  1. 當 b(進位)不為 0 時進入迴圈。
  2. 計算進位 carry = (a & b) << 1。
  3. 計算不進位和 a = a ^ b。
  4. 令 b = carry,迴圈結束後回傳 a。

Sum of Two Integers 複雜度分析

項目複雜度
時間複雜度O(1)
空間複雜度O(1)

迴圈次數最多等於位元數(32),與輸入數值大小無關,所以時間是 O(1)。只用兩個變數,空間 O(1)。

Sum of Two Integers 的邊界情況與常見錯誤

  • 負數在二補數表示下同樣適用,不需要特別處理符號。
  • 某些語言(如 Python)整數無限長,必須手動遮罩成 32 位元並處理負數還原。
  • a 與 b 其中一個為 0 時,迴圈不執行直接回傳另一個。
  • 左移可能溢位,在固定寬度整數的語言中這是預期行為。

Sum of Two Integers 其他解法比較

解法時間空間說明
用內建加法O(1)O(1)題目明令禁止
遞迴版全加器O(1)O(1)邏輯相同但有呼叫成本
迭代 XOR + AND 進位O(1)O(1)本文採用