Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in Scala: A 32-Step Shift Loop with Long

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

    SCALA · BIT MANIPULATION

    Reverse Bits in Scala, explained

    Problem overview

    The method reverseBits(n: Long): Long treats n as a binary number of exactly 32 bits, leading zeros included, reverses the order of those bits and returns the number the reversed bits form.

    For n = 1, the 32 bits are 31 zeros and a final 1. Reversed, the 1 moves to the front: 10000000000000000000000000000000, which is 2 to the power 31, 2147483648. For n = 43261596 the bits are 00000010100101000001111010011100 and the reversed bits 00111001011110000010100101000000 are 964176192.

    Approach: pop from one end, push to the other

    Take the bits of n from the right, one at a time, and push each one into a new number result from the right. The first bit taken enters first, then every later bit pushes it one place to the left. After 32 rounds, the bit taken first has moved 31 places and sits at the front: the order is reversed.

    Each round has three actions:

    • num & 1 reads the last bit of num.
    • result << 1 shifts result one place left, leaving a 0 at its right end, and | (OR) copies the bit into that 0.
    • num >>= 1 drops the bit that was just used, so the next one becomes the last.

    The loop must run exactly 32 times, even when num has become 0: the leading zeros of the input become the trailing zeros of the answer, and they need their shifts. Doing exactly 32 rounds takes constant time and space.

    Step by step

    1. Copy n into var num. A Scala parameter can't be reassigned, and the loop takes bits off num.
    2. Create var result = 0L. The L makes it a Long.
    3. Loop for (i <- 0 until 32), once per bit.
    4. Set result = (result << 1) | (num & 1).
    5. Shift num right with num >>= 1.
    6. Return result.

    The solution in Scala

    class Solution {
        def reverseBits(n: Long): Long = {
            var num = n
            var result = 0L
            for (i <- 0 until 32) {
                result = (result << 1) | (num & 1)
                num >>= 1
            }
            return result
        }
    }

    Why Long

    An Int is 32 bits and signed, so it tops out at 2147483647. The input can be as large as 4294967295 (one less than 2 to the power 32) and so can the answer, which is why the method uses Long. With an Int, the bit in position 31 is the sign bit: 1 << 31 evaluates to -2147483648, while 1L << 31 is 2147483648.

    Scala details

    • Both operands of | are Long: result is a Long, and num & 1 is a Long too, because num is. So there are no conversions in the loop.
    • >> is the arithmetic right shift, which copies the sign bit. For these inputs num is never negative, so it simply inserts zeros on the left. (>>> is the unsigned shift.)
    • num >>= 1 is the compound form of num = num >> 1.
    • 0 until 32 runs 32 times, for i from 0 to 31. The variable i isn't used inside; it only counts.

    Testing

    Results from the lesson's method:

    43261596   -> 964176192
    1          -> 2147483648
    4294967293 -> 3221225471
    0          -> 0
    4294967295 -> 4294967295
    2          -> 1073741824

    The last result shows the mirror effect: 2 is 10 at the right end, and reversed, its 1 lands in the second place from the left, which is 2 to the power 30.

    Complexity

    Time is O(1): the loop always runs 32 times, whatever n is. Space is O(1): two Longs.

    Edge cases and common mistakes

    • Stopping early: a loop like while (num != 0) stops once the input's bits run out and leaves the result too small. For n = 1 with only three rounds the result is 4, not 2147483648. All 32 rounds are needed.
    • Using Int: results above 2147483647 turn negative or lose bits. Keep the Long type in the signature and write the literal as 0L.
    • Shifting before reading: the order is shift result, OR in the bit, then shift num. Shifting result after the OR would move the new bit one place too far, and the answer would be doubled.
    • Palindromic bit patterns: a number whose bits read the same both ways, such as 4294967295, comes back unchanged. It is a handy sanity check.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free