371. Sum of Two Integers

  • Difficulty: Easy

  • Topics: Bit Manipulation

  • Similar Questions:

Problem:

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1

Solutions:

class Solution {
public:
    int getSum(int a, int b) {
        int ret = a^b;
        int carry = a&b;

        while (carry != 0) {
            // to prevent runtime exception, &0x7fffffff; This is not necessary for real program. Platforms other than leetcode do not complain. 
            carry = (carry & 0x7fffffff)<< 1; 
            int newRet = ret^carry;
            int newCarry = ret&carry;
            ret = newRet;
            carry = newCarry;
        }

        return ret;
    }
};

results matching ""

    No results matching ""