Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Reverse Bits

LeetCode #190Easy
build the answer bit by bit

Reverse the bits of an unsigned integer (the real problem is 32-bit; we use 8 bits here for clarity). 00101011 (43) becomes 11010100 (212).

Asked atAmazonApple
step 1 / 18
0
0
1
0
1
0
1
1
[0][1][2][3][4][5][6][7]
Build result bit by bit
1result = 0
2repeat WIDTH times:
3 result = (result << 1) | (n & 1) // pull lowest bit of n into result
4 n >>= 1 // discard that bit
5return result
state
  • n43 = 00101011
  • result0 = 00000000
  • width8

line 1Reverse the order of the bits. Here n = 43 = 00101011 (8 bits for the animation; the real LeetCode problem is 32-bit). We will build the answer one bit at a time, reading n from its LOWEST bit.