An interactive visualization of the Reverse Bits algorithm. Watch how each bit is extracted from the input number and placed in reverse order to build the output, reversing a 32-bit unsigned integer bit-by-bit.
Bit Manipulation LeetCode 190 โ Easy-3 and the output represents the signed integer -1073741825.
fun reverseBits(n: Int): Int { var result = 0; var num = n for (i in 0 until 32) { val bit = num and 1 result = (result shl 1) or bit num = num ushr 1 } return result
To reverse the bits, we extract bits from the right side of the input (least significant bit first)
and build the result from right to left by shifting and placing each bit. This effectively reverses
the entire 32-bit sequence. We use bitwise operations: & to extract, << to shift left,
| to place bits, and >> to shift right.
result = 0. This will hold our reversed bits.n using bit = n & 1.result = result << 1.result = result | bit.n = n >> 1.result contains all bits of n in reverse order.The algorithm always performs exactly 32 iterations (one per bit), regardless of the input value. Each iteration uses a constant amount of bitwise operations. Therefore, both time and space complexity are O(1).