Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in Rust: Shifting 32 Bits Into Place

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 6
    Ctrl + Enter to check

    RUST · BIT MANIPULATION

    Reverse Bits in Rust, explained

    Problem overview

    The function reverse_bits receives a u32, n, written with exactly 32 bits, leading zeros included. It reverses the order of those 32 bits: the last bit becomes the first, the second to last becomes the second, and so on. It returns the number that the reversed bits form.

    For n = 43261596 the 32-bit form is 00000010100101000001111010011100. Reversed, it is 00111001011110000010100101000000, which is 964176192. For n = 1 the single 1 bit moves from the last place to the first, giving 2147483648, which is 2^31. For n = 4294967293 the answer is 3221225471.

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

    Treat n as a stack of bits. The last bit of n is n & 1, and a right shift n >> 1 discards it and brings the next bit into last place. The answer is built the opposite way: a left shift result << 1 makes room at the right end, and OR puts the new bit there. The first bit taken from n is then shifted left by every later round, so after 32 rounds it sits at the far left. The last bit taken stays at the right. That is a reversal.

    The loop has to run exactly 32 times, not "until n is 0". Leading zeros of n are bits too, and they must become the trailing zeros of the answer. For n = 1, the first round puts a 1 at the right end of result and the 31 later rounds shift it left, one place per round, until it reaches the left end, which is the value 2147483648.

    Step by step

    1. Copy n into a mutable num. Function parameters are immutable in Rust, and the loop consumes the bits of num.
    2. Create result as a u32 starting at 0. It has to be the same type as num, because Rust combines only integers of one type.
    3. Loop 32 times with for _ in 0..32. The counter isn't used, so the underscore tells the compiler and the reader that it's deliberately ignored.
    4. Move one bit across. Shift result left by one, then OR in the last bit of num.
    5. Drop the bit just copied with num >>= 1, so the next bit becomes the last one.
    6. Return result as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn reverse_bits(n: u32) -> u32 {
            let mut num = n;
            let mut result: u32 = 0;
            for _ in 0..32 {
                result = (result << 1) | (num & 1);
                num >>= 1;
            }
            result
        }
    }
    

    Rust details worth knowing:

    • Why u32. The answer for n = 1 is 2147483648, which is larger than the biggest i32. An unsigned 32-bit integer holds 0 to 4294967295 and has exactly the 32 bits the problem talks about.
    • Right shifts differ by type. On an unsigned integer, >> fills the left end with 0s. On a signed integer it copies the sign bit, so -8i32 >> 1 is -4. With u32, the bits that arrive from the left are always 0, which is what this loop needs.
    • Bits that shift out are lost without a panic. A left shift by one place discards the top bit instead of failing. A shift by 32 or more places is different: it panics in a debug build, and the shifts here are always by 1.
    • (result << 1) | (num & 1). The parentheses aren't required, since shifts bind tighter than & and & tighter than |, but they make the two halves of the step obvious.
    • for _ in 0..32. The range holds the numbers 0 to 31, so the body runs 32 times. The standard library also offers n.reverse_bits(), which does the whole job for a u32.

    Complexity

    Time: O(1). The loop always runs 32 times, whatever n is.

    Space: O(1). The function keeps two integers.

    Edge cases and common mistakes

    • Zero and all ones. 0 returns 0, and 4294967295 returns 4294967295, since a reversed run of 1s is the same run.
    • Stopping when num is 0. A loop like while num != 0 skips the leading zeros. For n = 1 it would run once and return 1 instead of 2147483648.
    • Using i32. Inputs above 2147483647 don't exist in an i32, so the signature uses u32 for both n and the result.
    • Shifting in the wrong order. If result is shifted after the bit is added, the first bit is shifted 32 times instead of 31, so it falls off the left end and is lost.

    Testing

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