Bit Manipulation

75. Sum of Two Integers

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

Examples

Example 1

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

Example 2

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

Constraints

  • -1000 <= a, b <= 1000

Dados dos enteros a y b, devuelve la suma de ambos enteros sin usar los operadores + y -.

Ejemplos

Ejemplo 1

Entrada: a = 1, b = 2
Salida: 3

Ejemplo 2

Entrada: a = 2, b = 3
Salida: 5

Restricciones

  • -1000 <= a, b <= 1000
sum_of_two_integer.py
a: int
b: int
a, b = 3, 5
mask: int = 0xFFFFFFFF
while (b & mask) != 0:
    tmp: int = (a & b) << 1
    a = a ^ b
    b = tmp
if a > 0x7FFFFFFF:
    a = ~(a ^ mask)
print(a)
# <fixed>
# With negative numbers this entered an infinite loop because Python has arbitrary-precision
# integers and negative bits grow without bound. A 32-bit mask (0xFFFFFFFF) was added
# to simulate 32-bit integer overflow.
Keyboard shortcuts
h Previous problem
l Next problem
Esc Back to index
? Toggle this help