leetcode371: Sum of 2 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.

網上流傳最廣的方法:

原理:使用異或操作可以進行二進制不帶進位的加減,與操作可以得到進位。

即:

result0 = a ^ b

carry0 = (a & b) << 1

於是有:a + b = result0 + carry0

再進行一次迭代:

result1 = result0 ^ carry0

carry1 = (result0 & carry0) << 1

以此類推:有a + b = result0 + carry0 = result1 + carry1 = result2 + carry2 = ······ = resultN + carryN = result(N+1) ,直到carry(N+1)=0得到結果。

所以步驟是:
1、先讓兩個數字相加,但是不進位,即做異或的操作;
2、計算產生的進位,讓兩個數字位與操作,然後向左移動一位;
3、前兩步的結果相加,重複前兩個步驟直到進位爲0;

很容易寫出代碼:

public class SumOf2Int {
	static int getSum(int a, int b) {
		int x, y;
		while (b != 0){
			x = a ^ b;
			y = (a & b) << 1;
			a = x; b = y;
		}
		return a;
	}
	public static void main(String[] args) {
		System.out.println(getSum(-15, -5));
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章