Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in JavaScript: 32 Shifts and an Unsigned Result

Practice O(1) Read the full explanation

You are given a number n, written in binary with exactly 32 bits (leading zeros included).

Reverse the order of those 32 bits: the last bit becomes the first, the second to last becomes the second, and so on. Return the number that the reversed bits form.

 

Example 1:

Input: n = 43261596
Output: 964176192
Explanation: 43261596 in 32 bits is 00000010100101000001111010011100.
Reversed, the bits are 00111001011110000010100101000000, which is 964176192.

Example 2:

Input: n = 1
Output: 2147483648
Explanation: 1 is 00000000000000000000000000000001.
Reversed, its only 1 bit moves to the front: 10000000000000000000000000000000, which is 231 = 2147483648.

Example 3:

Input: n = 4294967293
Output: 3221225471
Explanation: 4294967293 is 11111111111111111111111111111101.
Reversed, the bits are 10111111111111111111111111111111, which is 3221225471.

 

Constraints:

  • 0 <= n <= 232 - 1
  • The answer is also between 0 and 232 - 1.
  • Numbers this large don't fit in a 32-bit signed integer, so n and the answer use a type that holds 232 - 1: the one in the starter code.
Note:

Your algorithm should run in O(1) time, one step for each of the 32 bits, and use O(1) extra space.



Take the bits of n one at a time from its right end: n AND 1 is the last bit, and shifting n one place right drops it, so the next bit becomes the last one. Where should each bit you take go in the answer?

Build the answer in result, starting from 0. In each round, shift result one place left, which leaves a 0 at its right end, and put the bit you took there with OR. Do it exactly 32 times, even after n has become 0: the first bit you took then ends up in the first of the 32 places.

The loop always runs 32 times, whatever n is: O(1) time.
We keep two numbers, so the extra space is O(1).
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · BIT MANIPULATION

    Reverse Bits in JavaScript, explained

    Problem overview

    The method reverseBits(n) receives a number written in binary with exactly 32 bits, leading zeros included. It reverses the order of those 32 bits and returns the number the reversed bits form. For n = 1, the 32-bit form is 31 zeros and a final 1. Reversed, the 1 moves to the front, giving 2147483648. For n = 43261596 the answer is 964176192.

    43261596   : 00000010100101000001111010011100
    964176192  : 00111001011110000010100101000000
    

    The statement asks for O(1) time, one step for each of the 32 bits, and O(1) extra space. Both n and the answer can be as large as 4294967295 (2**32 - 1), which is bigger than the largest signed 32-bit integer.

    Approach: take bits off one end, push them onto the other

    Take the bits of n one at a time from the right end: n & 1 is the last bit, and shifting n one place right drops it so the next bit becomes the last. Meanwhile, build result from the right: shift it one place left, which opens a 0 at the right end, and put the bit you took there with OR.

    The first bit taken is pushed left by every later round, so after 32 rounds it has moved 31 places and sits at the front. The second moved 30 places, and so on: each bit ends up in its mirror position.

    The loop must run exactly 32 times, even after n has become 0. The remaining rounds push zeros in, and they are what move the early bits to the front. With n = 1, the first round puts the 1 into result, and every later round just shifts it one place further left:

    round 0: n = 0, result = 1
    round 1: n = 0, result = 2
    round 2: n = 0, result = 4
    round 3: n = 0, result = 8
    

    After 32 rounds the 1 reaches the front.

    Step by step

    1. Create result with let, starting at 0.
    2. Loop 32 times with i from 0 while i < 32. All 32 bits must move, leading zeros included.
    3. Shift and insert: result = (result << 1) | (n & 1). The shift makes room, n & 1 isolates the last bit of n, and OR copies it into the free place.
    4. Shift n right with n >>>= 1, dropping the bit just used. The >>> operator fills the left end with 0, reading n as an unsigned 32-bit number, as the problem does.
    5. Return result >>> 0, the same 32 bits read as an unsigned number.

    The solution in JavaScript

    class Solution {
        /**
        * @param {number} n
        * @return {number}
        */
        reverseBits(n) {
            let result = 0;
            for (let i = 0; i < 32; i++) {
                result = (result << 1) | (n & 1);
                n >>>= 1;
            }
            return result >>> 0;
        }
    }
    

    The JavaScript details are the heart of this lesson:

    • Bit operators use signed 32-bit integers. <<, | and & convert their operands to signed 32-bit integers, and the result is signed too. When the first bit of result is 1, the number reads as negative: for n = 1, the loop leaves result equal to -2147483648.
    • >>> 0 reinterprets as unsigned. The unsigned right shift by zero changes no bits, but it produces a non-negative number, so -2147483648 >>> 0 is 2147483648. Without it, reverseBits(1) would return -2147483648 and reverseBits(4294967293) would return -1073741825, instead of 2147483648 and 3221225471.
    • >>>= versus >>=. >> keeps the sign by copying the left bit, while >>> fills with 0. Here the choice of shift on n doesn't change the answer, since 32 bits are read from the right end and the fill only affects bits that are never used, but >>> matches the unsigned reading of the input.
    • Inputs above 2147483647. n & 1 works on the low 32 bits of n, so values up to 4294967295 are read correctly. For example, -1 >>> 0 is 4294967295.
    • Compound assignment. n >>>= 1 is shorthand for n = n >>> 1. It changes only the local parameter.

    Complexity

    Time: O(1). The loop always runs 32 times, whatever n is, with a few bit operations per round.

    Space: O(1). Only result, n and the counter are stored.

    Edge cases and common mistakes

    • Zero. reverseBits(0) returns 0.
    • All bits set. reverseBits(4294967295) returns 4294967295: the reversed pattern of 32 ones is the same.
    • Forgetting >>> 0. This is the usual mistake in JavaScript. Any input whose lowest bit is 1 puts a 1 in the sign bit, and the method returns a negative number.
    • Stopping when n is 0. A loop like while (n !== 0) skips the leading zeros. For n = 1 it would return 1 instead of 2147483648, because the single bit never travels to the front.
    • Using result * 2 or + instead of << and |. They are equivalent in principle, but the lesson's bit operators keep everything in 32 bits and make the intent clear.
    • Doing the shift in the wrong order. Shift result first, then insert the bit. Inserting first and shifting afterwards leaves a 0 in the last place and an extra shift overall.

    Testing

    • n = 43261596 gives 964176192.
    • n = 1 gives 2147483648.
    • n = 4294967293 gives 3221225471.
    • n = 0 gives 0.
    • n = 2 gives 1073741824.
    • n = 3 gives 3221225472.
    • n = 4294967295 gives 4294967295.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free