Similar Problems

Similar Problems not available

Add Two Integers - Leetcode Solution

Companies:

LeetCode:  Add Two Integers Leetcode Solution

Difficulty: Easy

Topics: math  

Problem Statement:

Given two integers a and b, return the sum of them.

Constraints:

-1000 <= a, b <= 1000

Solution:

The problem is quite straightforward, we just need to add two integers. We can use the '+' operator for this.

We can simply write a function that takes two integer parameters and returns their sum. The solution in Python is given below:

def add_two_integers(a: int, b: int) -> int:
    return a + b

We can also solve this problem using the bit-wise operator.

def add_two_integers(a: int, b: int) -> int:
    while b != 0:
        carry = a & b
        a = a ^ b
        b = carry << 1
    return a

In the above solution, we are using the bit-wise operators '&', '|' and '<<'. We are using a while loop to perform the addition.

First, we take the bitwise AND of 'a' and 'b' and assign it to 'carry'. We then take the bitwise XOR of 'a' and 'b' and assign it to 'a'. We shift 'carry' one position to the left and assign it to 'b'.

We then repeat the above steps until 'b' becomes 0. Finally, we return the value of 'a'.

The time complexity of this solution is O(1) and the space complexity is also O(1).

Test Cases:

Let's test our solution with some test cases:

assert add_two_integers(1, 2) == 3
assert add_two_integers(0, 0) == 0
assert add_two_integers(-1, 1) == 0

Conclusion:

In this problem, we learned how to add two integers using both the '+' operator and the bit-wise operators '&', '|' and '<<'. The problem was quite straightforward and easy to solve.

Add Two Integers Solution Code

1