Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Reverse the bit order of an 8-bit value (bit 0 ↔ bit 7, …).

Problem: Reverse the bit order of an 8-bit value (bit 0 ↔ bit 7, …).
def rev8(x):
    r = 0
    for _ in range(8):
        r = (r << 1) | (x & 1); x >>= 1
    return r
print(rev8(0b00010110), rev8(1), rev8(0b10000000))
What is printed?
  1. A. 13 128 1
  2. B. 104 128 1
  3. C. 11 128 1
  4. D. 104 1 128

Correct answer: B. 104 128 1

Each step moves the lowest bit of x into the lowest position of r while r shifts left, so the first bit read ends up highest. 00010110 → 01101000 = 104; 1 → 10000000 = 128; 128 → 1. The loop must run exactly 8 times – stopping when x becomes 0 would give 13 for 22 (no trailing zeros added). O(bits).

More Coding Interview Problems questions

Exams that ask this topic