Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to shift bits to the right by one position.
DSA Rust
let mut n = num; let mut rev = 0; for _ in 0..32 { rev = rev << 1; rev |= n & 1; n = n [1] 1; } rev
Attempts:
3 left
💡 Hint
Common Mistakes
Using left shift '<<' instead of right shift '>>'.
Using addition '+' or subtraction '-' instead of bit shifts.
✗ Incorrect
We shift the bits of n to the right by 1 to process the next bit.
2fill in blank
mediumComplete the code to shift the reversed bits to the left by one position.
DSA Rust
let mut rev = 0; for _ in 0..32 { rev = rev [1] 1; rev |= n & 1; n = n >> 1; } rev
Attempts:
3 left
💡 Hint
Common Mistakes
Using right shift '>>' instead of left shift '<<'.
Using addition '+' or subtraction '-' instead of bit shifts.
✗ Incorrect
We shift rev to the left by 1 to make space for the next bit.
3fill in blank
hardFix the error in the code to correctly reverse bits of a 32-bit number.
DSA Rust
fn reverse_bits(num: u32) -> u32 {
let mut n = num;
let mut rev = 0;
for _ in 0..32 {
rev = rev << 1;
rev |= n & 1;
n = n [1] 1;
}
rev
}Attempts:
3 left
💡 Hint
Common Mistakes
Using left shift '<<' instead of right shift '>>'.
Using addition '+' or subtraction '-' instead of bit shifts.
✗ Incorrect
We must shift n to the right by 1 to process bits from least significant to most significant.
4fill in blank
hardFill both blanks to complete the code that reverses bits and returns the result.
DSA Rust
fn reverse_bits(num: u32) -> u32 {
let mut n = num;
let mut rev = 0;
for _ in 0..32 {
rev = rev [1] 1;
rev |= n & 1;
n = n [2] 1;
}
rev
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the shift directions for rev and n.
Using addition or subtraction instead of bit shifts.
✗ Incorrect
Shift rev left to make space, and shift n right to process next bit.
5fill in blank
hardFill all three blanks to create a function that reverses bits and prints the result.
DSA Rust
fn reverse_bits(num: u32) -> u32 {
let mut n = num;
let mut rev = 0;
for _ in 0..32 {
rev = rev [1] 1;
rev |= n & [2];
n = n [3] 1;
}
rev
}
fn main() {
let num = 43261596;
let reversed = reverse_bits(num);
println!("Reversed bits: {}", reversed);
}Attempts:
3 left
💡 Hint
Common Mistakes
Masking with 0 instead of 1.
Using wrong shift directions.
Forgetting to mask n before OR operation.
✗ Incorrect
Shift rev left, mask n with 1 to get last bit, shift n right to move to next bit.
