Bird
Raised Fist0
DSA C#programming

Reverse Bits of a Number in DSA C#

Choose your learning style10 modes available
Mental Model
Flip the order of bits in a number so the last bit becomes first and the first becomes last.
Analogy: Imagine reading a sentence backwards letter by letter, so the last letter comes first and the first letter comes last.
Original bits: 0 0 0 0 1 1 0 1
Reversed bits: 1 0 1 1 0 0 0 0
Dry Run Walkthrough
Input: number: 13 (binary 00001101), reverse all 8 bits
Goal: Reverse the bits of 13 so the output is the number with bits flipped
Step 1: Extract least significant bit (LSB) 1 and add to result
result bits: 00000001, number bits: 00000110
Why: Start reversing from the rightmost bit
Step 2: Shift result left and add next bit 0
result bits: 00000010, number bits: 00000011
Why: Make room for next bit on left and add it
Step 3: Shift result left and add next bit 1
result bits: 00000101, number bits: 00000001
Why: Continue building reversed bits
Step 4: Shift result left and add next bit 1
result bits: 00001011, number bits: 00000000
Why: Add last bit from original number
Step 5: Shift result left 4 more times adding 0 bits (since original number bits are 0)
result bits: 10110000, number bits: 00000000
Why: Complete 8-bit reversal by adding zeros
Result:
Reversed bits: 10110000 (decimal 176)
Annotated Code
DSA C#
using System;

class ReverseBits {
    public static byte ReverseBitsOfByte(byte n) {
        byte result = 0;
        for (int i = 0; i < 8; i++) {
            result <<= 1; // shift result left to make room for next bit
            result |= (byte)(n & 1); // add least significant bit of n to result
            n >>= 1; // shift n right to process next bit
        }
        return result;
    }

    static void Main() {
        byte number = 13; // 00001101
        byte reversed = ReverseBitsOfByte(number);
        Console.WriteLine($"Original: {Convert.ToString(number, 2).PadLeft(8, '0')}");
        Console.WriteLine($"Reversed: {Convert.ToString(reversed, 2).PadLeft(8, '0')}");
        Console.WriteLine($"Decimal reversed: {reversed}");
    }
}
result <<= 1; // shift result left to make room for next bit
Shift result left to add next bit on right side
result |= (byte)(n & 1); // add least significant bit of n to result
Add current rightmost bit of n to result
n >>= 1; // shift n right to process next bit
Move to next bit of n by shifting right
OutputSuccess
Original: 00001101 Reversed: 10110000 Decimal reversed: 176
Complexity Analysis
Time: O(1) because the number of bits (8) is fixed and loop runs constant times
Space: O(1) because only a few variables are used regardless of input
vs Alternative: Alternative methods using string conversion are slower and use more memory; bitwise operations are efficient and direct
Edge Cases
number is 0 (all bits zero)
Reversed bits remain 0
DSA C#
for (int i = 0; i < 8; i++) { ... }
number is 255 (all bits one)
Reversed bits remain 255
DSA C#
for (int i = 0; i < 8; i++) { ... }
number with alternating bits (e.g., 170 = 10101010)
Bits reversed correctly to 85 (01010101)
DSA C#
for (int i = 0; i < 8; i++) { ... }
When to Use This Pattern
When you need to reverse the order of bits in a number, use bitwise shifting and masking to build the reversed number efficiently.
Common Mistakes
Mistake: Shifting the original number left instead of right, causing infinite loop or wrong bits
Fix: Shift the original number right to process bits from least significant to most significant
Mistake: Not shifting the result left before adding new bit, causing bits to overwrite
Fix: Always shift the result left before adding the next bit to build reversed bits correctly
Summary
Reverses the bits of a byte by shifting and masking.
Use when you need to flip bit order for encoding, decoding, or bit manipulation tasks.
Shift the result left and add the least significant bit of the input repeatedly to reverse bits.

Practice

(1/5)
1. What does the operation of reversing bits of a number mean in simple terms?
easy
A. Adding 1 to the binary number
B. Changing all 0s to 1s and 1s to 0s
C. Shifting bits to the left by one position
D. Flipping the order of bits from left to right

Solution

  1. Step 1: Understand bit order

    Bits are arranged from left (most significant) to right (least significant).
  2. Step 2: Reverse means flip order

    Reversing bits means the leftmost bit becomes rightmost and vice versa.
  3. Final Answer:

    Flipping the order of bits from left to right -> Option D
  4. Quick Check:

    Reverse bits = flip order [OK]
Hint: Reverse bits means flip their order, not invert values [OK]
Common Mistakes:
  • Confusing reversing bits with bitwise NOT (inverting bits)
  • Thinking reversing means shifting bits
  • Assuming reversing adds or subtracts from the number
2. Which of the following C# code snippets correctly reverses the bits of a 4-bit number stored in an integer variable n?
easy
A. int reversed = 0; for(int i=0; i<4; i++) { reversed <<= 1; reversed |= (n & 1); n >>= 1; }
B. int reversed = 0; for(int i=0; i<4; i++) { reversed |= (n & 1) << i; n >>= 1; }
C. int reversed = n << 4;
D. int reversed = ~n;

Solution

  1. Step 1: Analyze the loop logic in int reversed = 0; for(int i=0; i<4; i++) { reversed <<= 1; reversed |= (n & 1); n >>= 1; }

    It shifts reversed left by 1, adds least bit of n, then shifts n right by 1, effectively reversing bits.
  2. Step 2: Check other options

    int reversed = 0; for(int i=0; i<4; i++) { reversed |= (n & 1) << i; n >>= 1; } does not reverse bits, it copies bits in same order. int reversed = n << 4; shifts bits left, not reverse. int reversed = ~n; inverts bits, not reverse.
  3. Final Answer:

    Option A code correctly reverses bits -> Option A
  4. Quick Check:

    Shift left + OR + shift right = reverse bits [OK]
Hint: Shift reversed left, OR with last bit, shift input right [OK]
Common Mistakes:
  • Using bitwise NOT (~) instead of reversing bits
  • Shifting bits without combining properly
  • Not updating reversed variable inside loop
3. What is the output of the following C# code snippet?
int n = 13; // binary 1101
int reversed = 0;
for (int i = 0; i < 4; i++) {
  reversed <<= 1;
  reversed |= (n & 1);
  n >>= 1;
}
Console.WriteLine(reversed);
medium
A. 11
B. 7
C. 13
D. 14

Solution

  1. Step 1: Convert 13 to 4-bit binary

    13 in binary (4 bits) is 1101.
  2. Step 2: Reverse bits step-by-step

    Bits: 1 1 0 1 reversed: 1 0 1 1 which is binary 1011 = decimal 11.
  3. Final Answer:

    11 -> Option A
  4. Quick Check:

    1101 reversed = 1011 = 11 [OK]
Hint: Reverse bits manually and convert to decimal [OK]
Common Mistakes:
  • Not limiting to 4 bits, causing wrong output
  • Confusing bit order when reversing
  • Assuming reversed number equals original
4. Identify the error in the following C# code that attempts to reverse bits of an 8-bit number:
int ReverseBits(int n) {
  int reversed = 0;
  for (int i = 0; i < 8; i++) {
    reversed |= (n & 1) << i;
    n >>= 1;
  }
  return reversed;
}
medium
A. The variable reversed should be initialized to 1
B. The loop should run 16 times for 8-bit numbers
C. The bits are not reversed; they are copied in the same order
D. The shift operator << is used incorrectly

Solution

  1. Step 1: Analyze bit placement in loop

    The code places bits at increasing positions without reversing order.
  2. Step 2: Understand reversing bits logic

    Reversing requires shifting reversed left and OR with last bit, not shifting bits by i.
  3. Final Answer:

    The bits are not reversed; they are copied in the same order -> Option C
  4. Quick Check:

    Shifting bits by i copies order, not reverse [OK]
Hint: Reversing needs shifting reversed left each step, not shifting bits by i [OK]
Common Mistakes:
  • Using bit shift by loop index instead of shifting reversed
  • Incorrect loop count for bit size
  • Initializing reversed incorrectly
5. You want to reverse the bits of a 16-bit unsigned integer and then check if the reversed number is a palindrome in binary (reads the same forwards and backwards). Which approach correctly combines reversing bits and palindrome check?
hard
A. Invert bits using bitwise NOT, then check if inverted equals original
B. Reverse bits using a loop shifting reversed left and OR with last bit, then compare reversed with original
C. Shift original number left by 16 bits, then compare with original
D. Reverse bits by shifting bits by index, then check if reversed equals original

Solution

  1. Step 1: Reverse bits correctly

    Use loop to shift reversed left, OR with last bit of original, shift original right.
  2. Step 2: Check palindrome by comparing reversed and original

    If reversed equals original, bits form a palindrome.
  3. Final Answer:

    Reverse bits using a loop shifting reversed left and OR with last bit, then compare reversed with original -> Option B
  4. Quick Check:

    Reverse bits + compare = palindrome check [OK]
Hint: Reverse bits properly, then compare to original for palindrome [OK]
Common Mistakes:
  • Using bitwise NOT instead of reversing bits
  • Shifting bits incorrectly causing wrong reverse
  • Comparing inverted bits instead of reversed bits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard