Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in Kotlin: Shifting 32 Bits 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

    KOTLIN · BIT MANIPULATION

    Reverse Bits in Kotlin, explained

    Problem overview

    The function reverseBits receives a Long named n, a number written in binary with exactly 32 bits, leading zeros included. It reverses the order of those 32 bits, so 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, also as a Long.

    For n = 43261596 the 32 bits are 00000010100101000001111010011100. Reversed, they are 00111001011110000010100101000000, which is 964176192. For n = 1, the only 1 bit moves from the last place to the first, giving 2147483648, which is 2 to the power of 31.

    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 one to the right end of a growing answer. The bit taken first goes in first, and every later bit pushes it one place to the left. After 32 rounds, the first bit taken has moved 31 places and sits at the front, and every other bit is in its mirrored place.

    Two operations do the work. num and 1L reads the last bit of num, and shifting num one place right drops that bit so the next one becomes the last. On the answer side, shifting result one place left makes room with a 0 at the right end, and or copies the bit into that 0.

    The loop must run exactly 32 times, even after num has become 0. The leading zeros of n are real bits of the 32-bit number, and they become the trailing zeros of the answer. Stopping early would leave the answer shifted too far to the right. With a fixed 32 rounds, the time is O(1).

    Step by step

    1. Copy n into num, a var, because Kotlin parameters are read-only. The loop takes bits off num.
    2. Create result as a var starting at 0L. The L makes the literal a Long, matching the return type.
    3. Loop i over 0 until 32. Every bit must move, zeros included.
    4. Push one bit into the answer: result = (result shl 1) or (num and 1L).
    5. Drop that bit from num: num = num shr 1.
    6. Return result.

    The solution in Kotlin

    class Solution {
        fun reverseBits(n: Long): Long {
            var num = n
            var result = 0L
            for (i in 0 until 32) {
                result = (result shl 1) or (num and 1L)
                num = num shr 1
            }
            return result
        }
    }
    

    To see the mechanism on a short number, here are the first six rounds for n = 13 (binary 1101), showing the bits of result and num after each round without leading zeros:

    round 1: result=1 num=110
    round 2: result=10 num=11
    round 3: result=101 num=1
    round 4: result=1011 num=0
    round 5: result=10110 num=0
    round 6: result=101100 num=0
    

    The bits of 13 come out in the order 1, 0, 1, 1, and the rounds after that push in zeros. After 32 rounds the first bit taken is the leading bit of the answer.

    The Kotlin details worth knowing:

    • Why Long. An Int holds up to 2147483647, but n and the answer can be as large as 4294967295. 1L shl 31 is 2147483648, while 1 shl 31 on an Int is -2147483648.
    • The L suffix. 0L and 1L are Long literals. They keep result a Long, so it can hold all 32 bits without wrapping into negative numbers.
    • Bit operators are words: shl, shr, and and or are infix functions.
    • shr is a signed shift. It copies the sign bit. Here num is never negative, since it is at most 4294967295 in a 64-bit Long, so the shift brings in zeros. ushr is the unsigned version, which would give the same result for these values.

    Complexity

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

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

    Edge cases and common mistakes

    • Zero. Every bit is 0, so the answer is 0.
    • All ones. 4294967295, which is 32 ones, reverses to itself.
    • Stopping when num is 0. For n = 1 the loop would stop after one round and return 1. Running all 32 rounds moves the bit to the front and gives 2147483648.
    • Using Int. Values from 2147483648 up don't fit, and the answer for n = 1 would turn negative.

    Testing

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