Description
Write a function that add two numbers A and B.
Clarification
Are a and b both 32-bit integers?
- Yes.
Can I use bit operation?
- Sure you can.
Challenge
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)
其实这道题就是让你写一个方法去计算A+B的和是多少。它的建议是可以直接返回 A + B 但是它建议不用算术运算符去完成。
Simple
public class Solution {
public int aplusb(int a, int b) {
return a + b;
}
}
Efficient
public class Solution {
public int aplusb(int a, int b) {
if(b == 0){
return a;
}
int aa = a ^ b;
int bb = (a & b) << 1;
return (aa, bb);
}
}
Notice
不进位的两数和可以通过 SUM = A ^ B
来计算
需要进位的两数和需要通过 SUM = (A & B) << 1
来计算