Python interview practice/Microsoft
Reverse Bits
Easydivide-and-conquer · bit-manipulation
The problem
Reverse bits of a given 32 bits unsigned integer.
Function: def reverseBits(n):
Example input (a JSON list of arguments): [43261596]
Expected output: 964176192
0 <= n < 2^32. Reverse exactly 32 bits, including leading zeroes.
Hints
- Shift exactly 32 input bits into a new integer in reverse order.
- Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.
Worked answer
Try it yourself first. When you are ready, open the answer below.
Show the Python answer
def reverseBits(n):
out=0
for _ in range(32):out=(out<<1)|(n&1);n>>=1
return outWhy it works
Shift exactly 32 input bits into a new integer in reverse order. The fixed width matters because leading zero bits become trailing zero bits; input is an unsigned 32-bit integer.
Complexity: O(32) time / O(1) fixed-width space.
Time: O(32) time · Space: O(1) fixed-width space
Run your own solution
Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Microsoft.
See access and price