[LintCode] A + B Problem

Write a function that add two numbers A and B. You should not use or any arithmetic operators.

There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.
Clarification

Are a and b both 32-bit integers?

  • Yes.

Can I use bit operation?

  • Sure you can.
Example

Given a=1 and b=2 return 3

Challenge 

Of course you can just return a + b to get accepted. But Can you challenge to not do it like that?

 

Analysis:  When adding two bits, we have the following 3 cases. These cases can be generalized in two steps. 1. add two bits. 2. add carry bit if any to the next higher bit.

0 + 0 = 0,     carry = 0

0 + 1 = 1,     carry = 0

1 + 1 = 0,     carry = 1

Consider two bitwise operators: bitwise and &, bitwise exclusive or ^.

0 ^ 0 = 0    0 & 0 = 0

0 ^ 1 = 1    0 & 1 = 0

1 ^ 1 = 0    1 & 1 = 1

^ operation matches step 1 adding two bits ignoring carry bits. & operation matches step 2 adding carry bits.

As a result, we can separate the above two steps by doing the following.

a ^ b represents adding all bits together ignoring all the carry bits.

(a & b) << 1 represents the addition result with only carry bits info. Each carry bit needs to be left shifted 1 bit to be at the right position.

After each round, we get two new numbers to add. Repeat this process until there is no carry bits.

 

class Solution {
    public int aplusb(int a, int b) {
        while(b != 0){
            int _a = a ^ b;
            int _b = (a & b) << 1;
            a = _a;
            b = _b;
        }
        return a;
    }
}

 

 

posted @ 2017-06-01 12:56  Review->Improve  阅读(213)  评论(0编辑  收藏  举报