LeetCode之Sum of Two Integers

94 阅读1分钟

1、题目

 

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.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

 

 

 

 

2、代码实现

 

public class Solution {
    public int getSum(int a, int b) {
    	 while(b != 0)  
    	    {  
    	        int tmp =(a & b) << 1; 
    	        //a是每次相加,相当于和
    	        a = a ^ b;
    	        //b相当于是进位
    	        b = tmp;
    	    }  
    	    return a;  
     }
}