Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in Swift: Shifting UInt32 in O(1) Time

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

    SWIFT · BIT MANIPULATION

    Reverse Bits in Swift, explained

    Problem overview

    The method reverseBits(_ n: UInt32) -> UInt32 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 bits are 31 zeros followed by a 1. Reversed, the 1 moves to the front, giving 10000000000000000000000000000000, which is 2147483648. For n = 43261596:

    00000010100101000001111010011100
    00111001011110000010100101000000
    

    The second line is the first one reversed, and its value is 964176192.

    The lesson asks for O(1) time (one step for each of the 32 bits) 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. n & 1 is the last bit, and shifting n one place right drops it, so the next bit becomes the last. Build the answer by shifting it one place left, which leaves a 0 at its right end, and putting the bit just taken into that place with OR.

    The first bit taken is pushed first, so every later round shifts it one place further left. After 32 rounds it has moved 31 places, to the front. The last bit taken stays at the right end. Each bit ends up in its mirrored position.

    The loop must run all 32 times, even after n has become 0. The leading zeros of n are the last bits taken, and they have to be pushed in so that the earlier bits reach the front.

    Step by step

    1. Copy n into var num. Swift parameters are constants, and the loop will take bits off num.
    2. Create result as a UInt32 starting at 0. Swift combines only numbers of the same type, so it has to match num.
    3. Loop 32 times over 0..<32. The counter is unused, so it is named _.
    4. Push a bit in: result = (result << 1) | (num & 1). The shift opens a 0 at the right end, num & 1 isolates the last bit of num, and OR copies it in.
    5. Drop the bit just used: num >>= 1.
    6. Return result.

    The solution in Swift

    class Solution {
        func reverseBits(_ n: UInt32) -> UInt32 {
            var num = n
            var result: UInt32 = 0
            for _ in 0..<32 {
                result = (result << 1) | (num & 1)
                num >>= 1
            }
            return result
        }
    }
    

    The Swift details worth a closer look:

    • UInt32. It is an unsigned 32-bit integer holding 0 to 4294967295. Both n and the answer can exceed the largest signed 32-bit value, 2147483647, so Int32 would not hold them. Its fixed width also means the top bit of result is really bit 31.
    • Shifts don't trap. << and >> discard the bits that fall off the end instead of crashing, unlike + and *, which trap on overflow. Here nothing useful is discarded: exactly 32 bits are pushed into a 32-bit value.
    • Same types. result << 1 and num & 1 are both UInt32, so the | between them type-checks. The literal 1 adapts to UInt32.
    • _ as the loop variable. It tells readers, and the compiler, that the counter isn't used.

    Watching the bits move

    For num = 6 (binary 110), here are the first four rounds, with each value printed without leading zeros:

    round 1: result=0 num=11
    round 2: result=1 num=1
    round 3: result=11 num=0
    round 4: result=110 num=0
    

    The first bit taken is 0, the second is 1, the third is 1 and the fourth is 0, so after four rounds result holds them as 0110 (printed as 110). The remaining 28 rounds keep shifting them left and push in zeros, because num is already 0.

    Complexity

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

    Space: O(1). Only num and result are stored.

    Edge cases and common mistakes

    • Zero. reverseBits(0) returns 0.
    • All ones. reverseBits(4294967295) returns 4294967295.
    • The top bit. reverseBits(2147483648), which has only the first bit set, returns 1.
    • Stopping when num is 0. A while num != 0 loop would skip the leading zeros. reverseBits(1) would return 1 instead of 2147483648.
    • Using Int for result. It doesn't compile next to UInt32 operands: Swift needs matching types, or an explicit conversion.
    • Shifting before taking the bit. The order matters: shift result and put the bit in first, and then drop that bit from num.

    Testing

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