Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in C#: Building the Answer with uint and Shifts

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

    C# · BIT MANIPULATION

    Reverse Bits in C#, explained

    Problem overview

    The method ReverseBits takes a uint n, read as exactly 32 bits with leading zeros included, and returns the uint formed by those bits in reverse order: the last bit becomes the first, the second to last becomes the second, and so on.

    For n = 1, the bits are 31 zeros and a final 1. Reversed, the 1 moves to the front, giving 2147483648 (2 to the power 31). For n = 43261596 the 32-bit form is 00000010100101000001111010011100, and the reversed bits 00111001011110000010100101000000 are 964176192.

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

    Take the bits of n one at a time from its right end. n & 1 is the last bit, and shifting n right by one drops it, so the next bit becomes the last. Meanwhile build result from the right: shift it left by one, which leaves a 0 at its right end, and copy the bit you took into that spot with OR.

    The first bit taken goes in first, and each later bit pushes it one place further left. After 32 rounds it has moved 31 places, to the front, which is the mirrored position. Every bit ends in its mirror place.

    The loop must run exactly 32 times, even once n has become 0. The leading zeros of n are real bits: they become the last bits of the answer, and the extra shifts of result are what move the early bits all the way to the front.

    Step by step

    1. Create result as a uint set to 0. uint is C#'s unsigned 32-bit integer, holding 0 to 4,294,967,295 (2 to the power 32, minus 1). That is the range of n and the answer, where an int stops at 2,147,483,647.
    2. Loop 32 times: int i from 0 while i < 32.
    3. Update result: result = (result << 1) | (n & 1);. Shifting left makes room, and OR copies the last bit of n into it.
    4. Shift n right: n >>= 1;. This discards the bit just copied, so the next one becomes the last.
    5. Return result.

    For the first example, printing the 32-bit forms of the input and of the method's result gives:

    00000010100101000001111010011100
    00111001011110000010100101000000
    

    The second line is the first read from right to left, and its value is 964176192.

    The solution in C#

    class Solution {
        public uint ReverseBits(uint n) {
            uint result = 0;
            for (int i = 0; i < 32; i++) {
                result = (result << 1) | (n & 1);
                n >>= 1;
            }
            return result;
        }
    }
    

    The C# details worth knowing:

    • Why uint. The answer for n = 1 is 2147483648, which is larger than int.MaxValue. With a uint the top bit is an ordinary bit, so the value stays positive.
    • Right shift on uint fills with zeros. On an int, >> copies the sign bit, so -1 >> 1 is still -1. On a uint, >> always brings in 0, which is what the loop needs.
    • Left shift drops overflowing bits. result << 1 on a uint discards the top bit if it is set, without an error. Here that can't lose data: result gets one bit per round, so after 32 rounds it holds exactly 32 bits.
    • n & 1 is a uint. Both operands are uint (the literal 1 fits), so it can be ORed with result directly, with no cast.
    • n is a copy. Shifting it doesn't change the caller's variable.

    Complexity

    Time: O(1). The loop always runs 32 times, whatever n is. Space: O(1). Two numbers and the loop counter.

    Edge cases and common mistakes

    • Zero and all ones. 0 returns 0, and 4294967295 (all 32 bits set) returns 4294967295.
    • Stopping when n reaches 0. For n = 1 that would stop after one round with result = 1 instead of 2147483648. The leading zeros must be processed.
    • Using int. n = 4294967293 doesn't fit in an int, and results above 2147483647 would come out negative. The signature uses uint for that reason.
    • Shifting before taking the bit. If you shift n right first, you lose the bit you meant to take.
    • Forgetting the parentheses. (result << 1) | (n & 1) reads clearly, and | has lower precedence than << and & anyway.

    Testing

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