Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result variable to zero.
DSA Javascript
function reverseBits(n) {
let result = [1];
// rest of the code
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result to n or 1 instead of 0.
✗ Incorrect
We start with result = 0 because we will build the reversed bits from scratch.
2fill in blank
mediumComplete the code to extract the least significant bit of n.
DSA Javascript
function reverseBits(n) {
let result = 0;
for(let i = 0; i < 32; i++) {
let bit = n [1] 1;
// rest of the code
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using OR or XOR instead of AND to extract bits.
✗ Incorrect
Using bitwise AND with 1 extracts the least significant bit.
3fill in blank
hardFix the error in shifting the result to the left before adding the bit.
DSA Javascript
function reverseBits(n) {
let result = 0;
for(let i = 0; i < 32; i++) {
let bit = n & 1;
result = (result [1] 1) | bit;
n = n >>> 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using right shift instead of left shift here.
✗ Incorrect
We shift result left by 1 to make room for the new bit on the right.
4fill in blank
hardFill both blanks to correctly shift n and update result in the loop.
DSA Javascript
function reverseBits(n) {
let result = 0;
for(let i = 0; i < 32; i++) {
let bit = n & 1;
result = (result [1] 1) | bit;
n = n [2] 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using signed right shift (>>) instead of unsigned (>>>).
✗ Incorrect
Shift result left to add bit, and shift n right logically to process next bit.
5fill in blank
hardFill all three blanks to complete the function that reverses bits of a number.
DSA Javascript
function reverseBits(n) {
let result = [1];
for(let i = 0; i < 32; i++) {
let bit = n [2] 1;
result = (result [3] 1) | bit;
n = n >>> 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using OR instead of AND to extract bit, or wrong initial value.
✗ Incorrect
Initialize result to 0, extract bit with AND, shift result left to add bit.
