leetcode371. 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.
这个就是基本的加法器(ALU)工作行为。
如果是单比特的a + b,那么结果应该是两位,姑且算是:x1, x0。
x1 = a & b;
x0 = a ^ b;
看看下面的计算表格就知道了:
这个是考虑机器加法所得
int getSum(int a, int b) {
int c = a & b;
int r = a ^ b;
return c == 0 ? r : getSum(r, c << 1);
}
这个是考虑数学
int getSum(int a, int b) {
return (int)log(exp(a)*exp(b));
}