原题网址:https://leetcode.com/problems/sum-of-two-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.
方法:手工实现二进制加法。
public class Solution {
public int getSum(int a, int b) {
int sum = a ^ b;
int carry = a & b;
while (carry != 0) {
carry <<= 1;
int ncarry = sum & carry;
sum ^= carry;
carry = ncarry;
}
return sum;
}
}