Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in TypeScript: Shifts and the Unsigned Right Shift

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

    TYPESCRIPT · BIT MANIPULATION

    Reverse Bits in TypeScript, explained

    Problem overview

    The method reverseBits receives a number n that is to be read as a binary number of exactly 32 bits, leading zeros included. It reverses the order of those 32 bits, so the last bit becomes the first, and returns the number the reversed bits form.

    For n = 43261596 the 32 bits are 00000010100101000001111010011100. Reversed they are 00111001011110000010100101000000, and the method returns 964176192. For n = 1 the single 1 bit moves from the end to the front, and the result is 2147483648. For n = 4294967293, which is thirty-one 1s with a 0 in second-to-last place, the result is 3221225471.

    The input and the answer can be as large as 4,294,967,295. The note asks for O(1) time, one step for each of the 32 bits, and O(1) extra space.

    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 that the next bit becomes the last. Meanwhile, build the answer in result by shifting it one place left, which leaves a 0 at its right end, and copying the bit taken from n into that place with OR.

    The first bit taken is pushed first, so every later bit pushes it one place further left. After 32 rounds it has moved 31 places, to the front, and each bit sits in its mirrored position. The loop must run all 32 times, even once n has become 0: the leading zeros of n become the trailing zeros of the answer, and skipping those rounds would leave the other bits too far right.

    The same idea on a 4-bit input, n = 11 (1011), shows how it builds up:

    round  result  n
    0      1       5
    1      3       2
    2      6       1
    3      13      0
    

    The result, 13, is 1101, which is 1011 reversed. For this lesson the loop runs 32 times instead of 4.

    Step by step

    1. Start result at 0, declared with let.
    2. Loop 32 times with i from 0 to 31. Each round moves one bit.
    3. Move a bit. (result << 1) | (n & 1) shifts result left, takes the last bit of n and ORs it into the free place.
    4. Drop that bit from n with n >>>= 1, so the next bit becomes the last one. The >>> operator fills the left end with 0 and reads n as an unsigned 32-bit number, as this problem does.
    5. Return result >>> 0. This reads the 32 bits as an unsigned number.

    The solution in TypeScript

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

    Some TypeScript details matter a lot here:

    • Bitwise operators work on signed 32-bit integers. number is a double, but <<, & and | first convert their operands to signed 32-bit integers and give back a signed result. When the first bit is 1, the value reads as negative: 1 << 31 is -2147483648.
    • >>> 0 turns the result back into an unsigned number. It keeps the same 32 bits and reads them as a number from 0 to 4,294,967,295. For example, -1 >>> 0 is 4294967295 and (1 << 31) >>> 0 is 2147483648. Without it, the method returns -2147483648 for n = 1, while 43261596 still gives 964176192 because its first reversed bit is 0.
    • >>> versus >>. >> keeps the sign bit and copies it in on the left, while >>> always brings in 0. With n = 2147483648, n >> 1 is -1073741824 and n >>> 1 is 1073741824. The input can be above 2,147,483,647, so >>>= is what makes the loop correct.
    • The input needs no conversion. n & 1 works for n up to 4,294,967,295, because the 32-bit conversion keeps the lowest 32 bits, and the lowest bit is what we read.
    • Types are erased. number says nothing about 32 bits. TypeScript has no separate unsigned integer type, so the shift trick is how an unsigned 32-bit value is represented.

    Complexity

    Time: O(1). The loop always runs 32 times, whatever n is, and each round does a constant amount of work.

    Space: O(1). The method keeps result and the loop counter, and reuses the parameter n.

    Edge cases and common mistakes

    • Zero. reverseBits(0) returns 0.
    • All ones. reverseBits(4294967295) returns 4294967295: the reversal changes nothing.
    • Stopping early. A loop like while (n !== 0) skips the leading zeros. For n = 1 it would run once and return 1 instead of 2147483648.
    • Forgetting >>> 0. Without it, any answer whose first bit is 1, such as 2147483648, comes out negative. For n = 1 the result is -2147483648.
    • Using >>= on n. For an input of 2147483648 or more, the sign bit is copied in on every shift and the later bits come out wrong.

    Testing

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