题目
原文:
Write a function that adds two numbers. You should not use + or any arithmetic operators.
译文:
写一个两个数相加的函数,你不能使用+号或其他算术运算符。
解答
不能使用算术运算符,就只能考虑用二进制的为运算符了。
一个方法是,对两个数的二进制数,分别进行不进位的按位求和(异或)、和只进位的按位求和:当(1,1)时,才会有进位,将下一位置为1(左移一位 <<1),该位置为0(并且注意不考虑进位后的下一位再进位);然后再递归求和,直至进位为0。
举个简单的例子,模拟下,7+5
转化为二进制 第一次运算 第二次运算
不进位 111 (7) 0010 (2) 1000 (8)
只进位 101 (5) 1010 (10) 0100 (4) 结果:1100 (即12)
代码如下:
class Q20_1{
public static void main(String[] args){
System.out.println(add_no_arithm(759,674));
System.out.println(add_no_arithm1(7,5));
}
public static int add_no_arithm(int a,int b){
if(b==0) return a;
int sum=a^b; //add without carrying
int carry=(a&b)<<1; //carry,but don't add
return add_no_arithm(sum,carry); //recurse
}
//recurse iteration
public static int add_no_arithm1(int a,int b){
while(b!=0){
int sum=a^b;
int carry=(a&b)<<1;
a=sum;
b=carry;
}
return a;
}
}
另外还有一种C语言的非常巧妙的解法,可参考:http://hawstein.com/posts/20.1.html
---EOF---