Cracking the coding interview--Q20.1

题目

原文:

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---


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值