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.
Tags:
Bit_Manipulation
2、Java代码实现
public class Solution {
public int getSum(int a, int b) {
if(a==0)
return b;
if(b==0)
return a;
while(b!=0){
int carry=a&b;
a=a^b;
b=carry<<1;
}
return a;
}
}
3、经验教训
- 后悔当初没好好学数字逻辑和组成原理,对Bit的操作都不熟练……
- Leetcode中一个比较好的discuss: Java simple easy understand solution with explanation,以下是其中代码:
// Iterative
public int getSum(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
// Iterative
public int getSubtract(int a, int b) {
while (b != 0) {
int borrow = (~a) & b;
a = a ^ b;
b = borrow << 1;
}
return a;
}
// Recursive
public int getSum(int a, int b) {
return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
}
// Recursive
public int getSubtract(int a, int b) {
return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);
}
// Get negative number
public int negate(int x) {
return ~x + 1;
}