标签:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Given a = 1 and b = 2, return 3.
public class Solution {
public int getSum(int a, int b) {
int r = 0, c = 0, recipe = 1;
while ((a | b | c) != 0) {
if (((a ^ b ^ c) & 1) != 0)
r |= recipe;
recipe <<= 1;
c = (a & b | b & c | a & c) & 1;
a >>>= 1;
b >>>= 1;
}
return r;
}
}
public class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int c = a & b; //carry
a ^= b; //add
b = c << 1;
}
return a;
}
}
【leetcode74】Sum of Two Integers(不用+,-求两数之和)
标签:
原文地址:http://blog.csdn.net/lpjishu/article/details/52073527