Bit Manipulation Counting and shifting bits

118. Reverse Bits

Easy 147 DSA Sheet

You are given a whole number n between 0 and 232 − 1. Write n in binary with exactly 32 digits, adding zeros on the left when it needs fewer. Reverse the order of those 32 digits and return the number they now spell.

The digits keep their values. Only their order changes: the rightmost digit of n becomes the leftmost digit of the answer, and the leftmost digit of n becomes the rightmost.

The answer is also between 0 and 232 − 1, and it is never negative. In C++, Java, Go, Rust and C#, n and the answer are 64-bit integers, because a signed 32-bit int cannot hold the numbers from 231 up. In Python and JavaScript they are ordinary numbers.

Example 1

Input: n = 11

Output: 3489660928

Explanation: In 32 digits, 11 is 0000 0000 0000 0000 0000 0000 0000 1011 (spaces added for reading). Reversed, it is 1101 0000 0000 0000 0000 0000 0000 0000, which is 231 + 230 + 228 = 3489660928.

Example 2

Input: n = 2147483648

Output: 1

Explanation: 2147483648 is 231, a single 1 in the leftmost of the 32 digits. Reversed, that 1 is the rightmost digit, so the answer is 1.

Example 3

Input: n = 4294967295

Output: 4294967295

Explanation: All 32 digits are 1, so their order makes no difference. This is the largest n, and its answer is the largest possible answer.

Check your understanding

Work out the answer for this input before you write any code.

n = 1

Constraints

  • 0 ≤ n ≤ 232 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.