Bit Manipulation

14. Reverse Bits

Reverse the bits of a given 32-bit signed integer.

Examples

Example 1

Input: n = 43261596
Output: 964176192
Explanation:
  43261596 -> 00000010100101000001111010011100
  964176192 -> 00111001011110000010100101000000

Example 2

Input: n = 2147483644
Output: 1073741822
Explanation:
  2147483644 -> 01111111111111111111111111111100
  1073741822 -> 00111111111111111111111111111110

Constraints

  • 0 <= n <= 2^31 - 2
  • n is even

Follow-up

If this function is called many times, how would you optimize it?

Invierte los bits de un entero con signo de 32 bits.

Ejemplos

Ejemplo 1

Entrada: n = 43261596
Salida: 964176192
Explicacion:
  43261596 -> 00000010100101000001111010011100
  964176192 -> 00111001011110000010100101000000

Ejemplo 2

Entrada: n = 2147483644
Salida: 1073741822
Explicacion:
  2147483644 -> 01111111111111111111111111111100
  1073741822 -> 00111111111111111111111111111110

Restricciones

  • 0 <= n <= 2^31 - 2
  • n es par

Desafio adicional

Si esta funcion se llama muchas veces, como la optimizarias?

reverse_bits.py
# Reverse the bits of a 32-bit unsigned integer
n: int = 2147483644
res: int = 0
for i in range(32):
    bit: int = (n >> i) & 1
    res = res | (bit << (31 - i))
print(res)
Keyboard shortcuts
h Previous problem
l Next problem
Esc Back to index
? Toggle this help