题目:
Write a function that adds two numbers. You should not use '+' or any arithmetic operators.
P.S. CC150最后一章的第一题。
分析:
用759+674作为例子:如果不算carry,那么sum1=323; 只算carry,那么sum2=1110,最终,sum=sum1+sum2=1433。
计算机内的加法,大体如此,不过是二进制罢了。
而二进制的加法不用'+',可以用位运算解决:a^b表示的就是不算carry,(a&b)<<1表示的就是carry的运算。
加上递归,当carry递归到0的时候,即解。
Code:
class Test{
public static void main(String[] args){
Test test = new Test();
int a = 759, b = 674;
System.out.println(test.add(a, b));
}
public int add(int a, int b){
if(b == 0) return a;
int sum = a ^ b, carry = (a&b)<<1;
return add(sum, carry);
}
}
总结:
递归+位运算。