leetcode 371. 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.
不用加减法进行求和运算。
用^
来实现二进制的加法,同时用移位来进行进位。 可以用while循环来进行模拟操作,当不用进位的时候,跳出即可。
class Solution {
public:
int getSum(int a, int b) {
while (b) {
int c = a ^ b;
b = (a & b) << 1;
a = c;
}
return a;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号:
