Challenge - 5 Problems
Bit Reversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of reversing bits for a small number
What is the output of reversing the bits of the 8-bit number 13 (00001101 in binary)?
DSA Typescript
function reverseBits8(n: number): number {
let result = 0;
for (let i = 0; i < 8; i++) {
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
}
console.log(reverseBits8(13));Attempts:
2 left
💡 Hint
Think about reversing the bits from right to left for 8 bits.
✗ Incorrect
The binary of 13 is 00001101. Reversing bits gives 10110000 which is 176 in decimal.
❓ Predict Output
intermediateOutput of reversing bits for a 4-bit number
What is the output of reversing the bits of the 4-bit number 9 (1001 in binary)?
DSA Typescript
function reverseBits4(n: number): number {
let result = 0;
for (let i = 0; i < 4; i++) {
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
}
console.log(reverseBits4(9));Attempts:
2 left
💡 Hint
Reverse the bits of 1001 to get the answer.
✗ Incorrect
The binary of 9 is 1001. Reversing bits gives 1001 which is 9 in decimal.
🔧 Debug
advancedIdentify the error in reversing bits function
What error does the following TypeScript code produce when reversing bits of a 16-bit number?
DSA Typescript
function reverseBits16(n: number): number {
let result = 0;
for (let i = 0; i < 16; i++) {
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
}
console.log(reverseBits16(1));Attempts:
2 left
💡 Hint
Check the loop condition and how many bits are processed.
✗ Incorrect
The loop runs 17 times (i from 0 to 16 inclusive), shifting bits one extra time causing the result to be 65536 instead of 1.
🧠 Conceptual
advancedUnderstanding bit reversal effect on number size
If you reverse the bits of a 32-bit unsigned integer, which of the following statements is true?
Attempts:
2 left
💡 Hint
Think about how reversing bits changes the position of 1s and 0s.
✗ Incorrect
Reversing bits changes the position of bits, so the number can become larger or smaller depending on where the 1s are.
🚀 Application
expertResult after reversing bits and adding
Given the 8-bit number 85 (binary 01010101), what is the decimal result after reversing its bits and adding the original number?
DSA Typescript
function reverseBits8(n: number): number {
let result = 0;
for (let i = 0; i < 8; i++) {
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
}
const original = 85;
const reversed = reverseBits8(original);
const sum = original + reversed;
console.log(sum);Attempts:
2 left
💡 Hint
Reverse 01010101 and add to original number.
✗ Incorrect
85 in binary is 01010101. Reversed bits are 10101010 which is 170. Sum is 85 + 170 = 255.
