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?- A. 13 128 1
- B. 104 128 1
- C. 11 128 1
- 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
- Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows. java int a…
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '' + text to…
- Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together…
- Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it…
- Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros…
- Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros…