Sum of Two Integers - Medium - L

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/sum-of-two-integers/

Given two integers a and b, return the sum of the two integers without using the operators + and -.

Approach

  • Half-adder

Solution

class Solution {
public:
    int getSum(int a, int b) {
        while(b!=0){
            int carry = a&b;
            a = a^b;
            b = (unsigned int) carry<<1;
        }
        return a;
    }
};