Skip to content

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

  1. Shift exactly 32 input bits into a new integer in reverse order.
  2. 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 out

Why 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

More free Microsoft questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.