The Indian Engineer

Problem 371 Sum of Two Integers

Posted on Last edited 2 mins

Bit-Manipulation

Problem Statement

Link - Problem 371

Question

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

Example 1

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

Example 2

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

Constraints

Solution

class Solution {
public:
    int getSum(int a, int b) {
        if(b==0)
            return a;
        else
            return getSum(a^b,(a&b)<<1);
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Bit Manipulation O(1) O(1)

Explanation

1. Intuition

We need to do this until there is no carry left.

2. Implementation

Iterative Approach

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