Reverse Bits - Problem

Reverse bits of a given 32-bit unsigned integer.

Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.

In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 below, the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Input & Output

Example 1 — Basic Case
$ Input: n = 43261596
Output: 964176192
💡 Note: Binary of 43261596 is 00000010100101000001111010011100. Reversing gives 00111001011110000010100101000000 which is 964176192 in decimal.
Example 2 — Negative Number
$ Input: n = -3
Output: -1073741825
💡 Note: Binary of -3 (in 32-bit) is 11111111111111111111111111111101. Reversing gives 10111111111111111111111111111111 which is -1073741825 in decimal.
Example 3 — Edge Case
$ Input: n = 1
Output: -2147483648
💡 Note: Binary of 1 is 00000000000000000000000000000001. Reversing gives 10000000000000000000000000000000 which is -2147483648 in decimal.

Constraints

  • The input must be a 32-bit unsigned integer
  • -2³¹ ≤ n ≤ 2³¹ - 1

Visualization

Tap to expand
Reverse Bits - Optimal Solution INPUT n = 43261596 32-bit Binary: 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 Position: 31 .... 16 | 15 .... 0 Hex: 0x02950C4C Input: 43261596 Unsigned 32-bit integer MSB at position 31 LSB at position 0 Read direction ALGORITHM STEPS 1 Initialize result = 0 Start with empty 32-bit result 2 Loop 32 times Process each bit position 3 Shift and Extract result = result << 1 result |= (n & 1) 4 Shift input right n = n >> 1 Bit Operation Visual n & 1 Get LSB res<<1 Make room res|=bit Add bit FINAL RESULT Result = 964176192 Reversed 32-bit Binary: 0 0 1 1 1 0 0 1 0 0 1 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 Hex: 0x3964A500 Output: 964176192 OK - Bits Reversed! Verification: Original bit 0 --> Result bit 31 Original bit 1 --> Result bit 30 ... Original bit 31 --> Result bit 0
Asked in
Apple 15 Airbnb 8
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending

Select Compiler

Choose a programming language

Compiler list would appear here...