Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result variable to zero.
DSA Rust
let mut result = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result to 1 or None causes wrong calculations.
✗ Incorrect
The result variable should start at 0 to accumulate the integer value.
2fill in blank
mediumComplete the code to get the integer value for a Roman numeral character.
DSA Rust
let value = match c {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => [1],
};Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 or None silently ignores invalid input.
✗ Incorrect
If the character is invalid, the code should panic to indicate an error.
3fill in blank
hardFix the error in the condition to check if the current value is less than the next value.
DSA Rust
if value [1] next_value { result -= value; } else { result += value; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses the logic and causes wrong results.
✗ Incorrect
If the current value is less than the next, subtract it according to Roman numeral rules.
4fill in blank
hardFill both blanks to iterate over the characters and get the next value safely.
DSA Rust
for i in 0..s.len() { let c = s.chars().nth(i).unwrap(); let value = roman_to_int(c); let next_value = if i + 1 < s.len() [1] else [2]; // rest of logic }
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic! causes program to crash unnecessarily.
✗ Incorrect
If there is a next character, get its value; otherwise, use 0 to avoid errors.
5fill in blank
hardFill all three blanks to complete the function that converts a Roman numeral string to an integer.
DSA Rust
fn roman_to_integer(s: &str) -> i32 {
let mut result = [1];
for i in 0..s.len() {
let c = s.chars().nth(i).unwrap();
let value = match c {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => panic!("Invalid character"),
};
let next_value = if i + 1 < s.len() [2] else [3];
if value < next_value {
result -= value;
} else {
result += value;
}
}
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling roman_to_integer recursively causes infinite loop.
✗ Incorrect
Initialize result to 0; get next value with roman_to_int; use 0 if no next char.
