Programming

Leetcode-371. Sum of Two Integers

Leetcode-371. Sum of Two Integers

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

<解題>

  1. 這題要做兩個數字的加法,但不可以運用+-符號,所以需要運用其他符合來完成
  • 運用carry = a & b 可以得到 a 和 b 的需進位結果
  • 運用a ^ b 可以得到 a 和 b 的不進位加法結果
  • 最後向左進一位
  1. 更新 a 的值為不進位加法的結果,b 的值為進位 carry 的值。當b變為0時,即進位為0,while 循環結束

class Solution {
    public int getSum(int a, int b) {
	if (a == 0) return b;
	if (b == 0) return a;

// a = 010 ; b = 011 
	while (b != 0) {
		int carry = a & b; //carry = 010 // carry =000 //a & b 可以得到 a 和 b 的需進位結果
		a = a ^ b;         //a = 001     // a = 101    //a ^ b 可以得到 a 和 b 的不進位加法結果
		b = carry << 1;    //b = 100     / /b = 000     //進位進一位
	}
	
	return a; //101
}
}

Time: O(k) (k為二進制的位數)

Space: O(1)

**可以和 67. Add Binary做比較