371. Sum of Two Integers java solutions

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.

 1 public class Solution {
 2     public int getSum(int a, int b) {
 3         int sum = a^b;//保留二进制和中两位不相同的位
 4         int carry = a&b;//保留二进制中两个都为1 的位置
 5         int tmp = 0;
 6         while(carry != 0){
 7             carry = carry << 1;// 通过移位来循环计算,将值加上
 8             tmp = sum;
 9             sum ^= carry;
10             carry &= tmp;
11         }
12         return sum;
13     }
14 }

这是leetcode 比较新的一题,挺有意思的。

posted @ 2016-07-04 15:43  Miller1991  阅读(145)  评论(0编辑  收藏  举报