reverse-bits.py
bit-manipulation/reverse-bits.py · Python · 390 B · 2026-03-09 21:43
# The bits in the reversed number are in the 31-i position, so we check if the bit in the i position of n is set, and if it is, we set the bit in the 31-i position of res. # bit # O(1) time, O(1) space def reverseBits(self, n: int) -> int: res = 0 for i in range(32): mask = 1 << i isset = mask & n if isset: res |= 1 << (31 - i) return res