371. Sum of Two Integers πŸ”₯

Medium

Problem:

Find the sum of two integers, a and b. You cannot use the + or - operators.

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

https://leetcode.com/problems/sum-of-two-integers/arrow-up-right

What to learn:

Implementation of Full Adder in Python

MASK acts as a bit mask, facilitating the creation of two's complement for handling negative numbers. Here, we assume the input value is a 32-bit integer with all its bits set to 1, so MASK is set to 0xFFFFFFFF.

  • If it exceeds the maximum 32 bits, the masking operation removes the exceeding value.

  • For negative numbers, since the Most Significant Bit (MSB) is 1, XOR it with the masking value and then apply NOT to revert it to a negative number.

Solution:

Simpler Full Adder

This loop continues until there is no carry left (i.e., b == 0). Each iteration, a becomes the sum without considering the carry, and b becomes the carry. The carry is then added in the subsequent iteration. The & MASK part ensures that we are only considering the least significant 32 bits of both a and b.

  • a: It holds the sum of a and b without considering the carry value.

  • b: It holds the carry value as the bits are advanced.

Java integer is a number of 32 bits

Reference: https://www.youtube.com/watch?v=gVUrDV4tZfYarrow-up-right

Last updated