leetcode 371. Sum of Two Integers

257 篇文章 17 订阅

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.


这道题就让我们看看大神们的方法吧!

public int getSum(int a, int b) {
     if(b == 0){//没有进位的时候完成运算
        return a;
    }
    int sum,carry;
    sum = a^b;//完成第一步加法的运算
    carry = (a&b)<<1;//完成第二步进位并且左移运算
    return getSum(sum,carry);//
}

这个思路大概类似于将0010和0011做加法,利用异或得到和,因为1+0=1,而1^0=1;0+0=0,1+1=0,而0^0=0,1^1=0,进位的话可以用&(与运算),对于1+0和0+0,没有进位,正好1&0=0,0&0=0,而1+1的进位为1,正好1&1=1。当然还要记得进位左移1位。

有大神甚至连同减法也顺便做了一下:

// Iterative
public int getSum(int a, int b) {
	if (a == 0) return b;
	if (b == 0) return a;

	while (b != 0) {
		int carry = a & b;
		a = a ^ b;
		b = carry << 1;
	}
	
	return a;
}

// Iterative
public int getSubtract(int a, int b) {
	while (b != 0) {
		int borrow = (~a) & b;
		a = a ^ b;
		b = borrow << 1;
	}
	
	return a;
}

按道理说负数是取反加一啊,而且a是被除数,为什么是(~a)&b呢?有人提出了相同的疑惑。

8
W
 

In the getSubtract method, why int borrow = (~a) & b instead of int borrow = ((~a)+1) & b;

reply quote 


这时就有人给出了完美的解释

7
S
 

@Wayne3223
It depends whether 'a' is the minuend(被除数) or subtrahend(除数).
i.e. difference = minuend - subtrahend.

If you write it as "2-3", and see 'a' as 3, and 'b' as 2. then the formula should be
borrow = ((~a)+1) & b;

See an example here. When b becomes 0, a = -1.
a = 3
b = 2

a = 0011
b = 0010

borrow = 1101 & 0010 = 0001
a = 0001
b = 0010

borrow = 1111 & 0010 = 0010
a = 0011
b = 0100

borrow = 1101 & 0100 = 0100
a = 0111
b = 1000

borrow = 1001 & 1000 = 1000
a = 1111
b = 0000

so a = -1;

However, if you write it as just "3 - 2", and take 'a' as 3 and 'b' as 2, then formula for borrow is
borrow = (~a) & b;

See an example below.
subtract 2 from 3.
a = 3
b = 2

a = 0011
b = 0010

borrow = 1100 & 0010 = 0000
a = 0001
b = 0000

a = 1;

So I believe it depends on the position of a.
If it is a - b then borrow = (~a) & b;
else if it is b - a then borrow = ((~a)+1) & b; or (~b) & a;
Honestly, I prefer the former one.
Correct me if anything is wrong here.

reply quote
 






大体意思就是说取决于a是被除数还是除数。如果是a-b,就是(~a)&b。如果是b-a,就是(-a+1)&b。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值