Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result variable to zero.
DSA C++
unsigned int reverseBits(unsigned int n) {
unsigned int result = [1];
for (int i = 0; i < 32; i++) {
// loop body
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result with n instead of 0.
Using -1 which sets all bits to 1.
✗ 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 C++
unsigned int reverseBits(unsigned int n) {
unsigned int result = 0;
for (int i = 0; i < 32; i++) {
unsigned int bit = n [1] 1;
// process bit
n >>= 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using OR or XOR instead of AND.
Using shift operators instead of bitwise AND.
✗ Incorrect
Using bitwise AND with 1 extracts the least significant bit of n.
3fill in blank
hardFix the error in updating the result by shifting and adding the bit.
DSA C++
unsigned int reverseBits(unsigned int n) {
unsigned int result = 0;
for (int i = 0; i < 32; i++) {
unsigned int bit = n & 1;
result = (result [1] 1) | bit;
n >>= 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using right shift instead of left shift.
Using addition instead of bitwise OR.
✗ Incorrect
We shift result left by 1 to make space for the new bit, then add it with OR.
4fill in blank
hardFill both blanks to complete the loop that reverses bits correctly.
DSA C++
unsigned int reverseBits(unsigned int n) {
unsigned int result = 0;
for (int i = 0; i < [1]; i++) {
unsigned int bit = n [2] 1;
result = (result << 1) | bit;
n >>= 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Looping 16 times instead of 32.
Using OR instead of AND to extract bits.
✗ Incorrect
We loop 32 times for 32 bits and use bitwise AND to get the last bit.
5fill in blank
hardFill all three blanks to create a function that reverses bits of an unsigned int.
DSA C++
unsigned int reverseBits(unsigned int n) {
unsigned int result = [1];
for (int i = 0; i < [2]; i++) {
unsigned int bit = n [3] 1;
result = (result << 1) | bit;
n >>= 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting result with 1 instead of 0.
Looping fewer than 32 times.
Using | instead of & to extract bits.
✗ Incorrect
Initialize result to 0, loop 32 times, and use & 1 to get the last bit.
