A right C++ answer on Sum of Two Integers without using + operator


  • 1
    G

    Solve it in bitwise, and make sure both x and y are >= zero.

    Step 1: If you ignore the carry, say 0+0=1, 0+1=1, 1+0=1, 1+1=0, this is xor operation, ^
    Step 2: Apparently, 1+1 you will get 10, that is 10=(1&1)<<1.
    Step 3: Add the return of step 1 and step 2, and continue step 1 and step 2 until carry is 0.

    Here is the CPP code

    class Solution {
    public:
        int getSum(int x, int y)
        {
            if ( 0 == y ) return x;
     
            int sum = x ^ y;
            int carry = (x & y) << 1;
            return getSum(sum, carry);
        }
    };

  • 0
    Y

    What if x = -1 and y = 1?
    It will get a wrong answer .


  • 0
    G

    Hi, please make sure both x and y is >= zero. My solution only works in that condition.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.