Description
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.
Solution 1(C++)
class Solution {
public:
int getSum(int a, int b) {
while((a&b) != 0){
int m=a^b, n=(a&b)<<1;
a=m;b=n;
}
return (int)a^b;
}
};
算法分析
这一道题怎么说呢,虽然面试不太会考,但我觉得这也算是程序员的基本功吧,熟练掌握二进制位运算与十进制四则运算之间相互转换的方法。思路非常重要。我不打算解释。还是希望以后看到这道题能再想一想。
程序分析
这一道题我刚开始答案是错的。查了一会才发现,啊,原来是C++中运算符的优先级没有注意到。这个真的是很惭愧。所以特定总结一下,加强记忆。参考:C++ 运算符的优先级和结合性。