LeetCode oj 371. Sum of Two Integers(位運算)

371. Sum of Two Integers

 
 My Submissions
  • Total Accepted: 37210
  • Total Submissions: 71785
  • Difficulty: Easy

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.

給你兩個數,不允許用加減運算符,求sum值

不允許用加法和減法,那麼肯定也不能用乘法除法,因爲乘法和除法是基於加法減法實現的,所以第一想法就是位運算。

先看異或運算 1 ^ 1 = 0 ,0 ^ 1 = 1,1 ^ 0 = 1, 0 ^ 0 = 0,再來看加法,不考慮進位的情況下,1 + 1 = 0,1 + 0 = 1,0 + 1 = 1,0 + 0 = 0,所以可以把異或運算

看成不考慮進位的加法。那麼我們需要考慮的就是怎麼處理進位了,顯然相同位置都爲1時纔會進位,這正好符合&運算,又因爲進位是進到高位上,

所以爲(a & b) << 1,這麼一直處理,直到一個數爲0。

public class Solution {
   	public int getSum(int a, int b) {
		while(a != 0){
			int temp = (a & b) << 1;
			b = a ^ b;
			a = temp;
		}
		return b;
	}
}



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