Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in Go: A 32-Round Loop with uint32

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

    GO · BIT MANIPULATION

    Reverse Bits in Go, explained

    Problem overview

    The function reverseBits receives a uint32 n, a number written in binary with exactly 32 bits, leading zeros included. It returns the number formed by those 32 bits in reverse order: the last bit becomes the first, the second to last becomes the second, and so on.

    For n = 43261596 the 32 bits and their reversal are:

    00000010100101000001111010011100
    00111001011110000010100101000000
    

    The reversed bits form 964176192. For n = 1, the lone 1 bit moves from the end to the front, and the answer is 2147483648, which is 2 to the power 31. For n = 4294967293 the answer is 3221225471.

    The lesson asks for O(1) time, one step per bit of a 32-bit number, and O(1) extra space.

    Approach: take bits from the right, push them in from the right

    Take the bits of n one at a time from its right end, and add each to a new number result from its right end too. The first bit taken ends up shifted left by every later round, so it finishes at the far left. The last bit taken is never shifted, so it stays at the far right. That is exactly a reversal.

    One round does two things:

    1. Shift result one place left, which leaves a 0 in its last place, and copy the last bit of n, which is n & 1, into that place with OR.
    2. Shift n one place right, which drops the bit just copied, so the next bit becomes the last one.

    The loop must run exactly 32 times, even after n has become 0. The leading zeros of n are bits too: they become the trailing zeros of the answer. Stopping early when n reaches 0 would leave the other bits too far to the right.

    For n = 1, the 1 enters result in the first round and is then shifted left 31 more times. The results after rounds 1, 2, 31 and 32 are 1, 2, 1073741824 and 2147483648. For n = 43261596 the first rounds look like this in binary:

    round 1 result=0 n=00000001010010100000111101001110
    round 2 result=0 n=00000000101001010000011110100111
    round 3 result=1 n=00000000010100101000001111010011
    round 4 result=11 n=00000000001010010100000111101001
    

    The number 43261596 ends in 00, so the first two bits taken are 0, and then come two 1s.

    Step by step

    1. Declare result with var as a uint32, starting at 0. It must have the same type as n.
    2. Write a loop that runs 32 times: i from 0 while i < 32. All 32 bits move, leading zeros included.
    3. Shift and insert. Inside the loop, set result to (result << 1) | (n & 1).
    4. Drop the bit you used with n >>= 1.
    5. Return result after the loop.

    The solution in Go

    func reverseBits(n uint32) uint32 {
        var result uint32 = 0
        for i := 0; i < 32; i++ {
            result = (result << 1) | (n & 1)
            n >>= 1
        }
        return result
    }
    

    The Go details worth knowing:

    • Why uint32. The values go up to 4294967295, which does not fit in a signed 32-bit integer. uint32 holds 0 to 4294967295 exactly.
    • Types do not mix. Go combines only numbers of the same type. Adding an int to a uint32 is a compile error: invalid operation: count + n (mismatched types int and uint32). Convert explicitly, as in uint32(x), when you need to.
    • Left shifts discard overflow. In result << 1, a bit pushed past the 32nd place is dropped silently. The loop never relies on it, because after 32 rounds result holds exactly 32 bits.
    • Right shifts on unsigned numbers fill with 0. n >>= 1 brings in a 0 at the left, so n reaches 0 after at most 32 rounds. On a signed negative number, Go would copy the sign bit instead.
    • Parameters are copies. Changing n inside the function does not affect the caller's variable.

    Complexity

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

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

    Edge cases and common mistakes

    • Zero and all ones. reverseBits(0) is 0, and reverseBits(4294967295) is 4294967295, since every bit is the same.
    • A single high bit. reverseBits(2147483648) is 1, the mirror of the n = 1 example.
    • Stopping when n is 0. The leading zeros would never be pushed into result, and the answer would come out too small. That is why the loop counts 32 rounds instead of testing n.
    • Using a different type for result. The statement result = (result << 1) | (n & 1) mixes result with n, so both must be uint32. Declaring result as an int is a type mismatch.
    • Reversing twice. reverseBits(reverseBits(43261596)) returns 43261596 again.

    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.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free