Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result variable to zero.
DSA C++
int romanToInt(string s) {
int result = [1];
// rest of the code
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result to 1 or negative values causes incorrect sums.
Using the length of the string as initial value is wrong.
✗ Incorrect
The result should start at 0 because we will add values to it as we process the Roman numerals.
2fill in blank
mediumComplete the code to get the integer value of a Roman numeral character.
DSA C++
int value(char r) {
if (r == 'I') return 1;
else if (r == 'V') return 5;
else if (r == 'X') return 10;
else if (r == 'L') return 50;
else if (r == 'C') return 100;
else if (r == 'D') return 500;
else if (r == 'M') return 1000;
else return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning -1 causes wrong subtraction.
Returning 1 or 1000 adds wrong values.
✗ Incorrect
If the character is not a valid Roman numeral, return 0 to avoid adding any value.
3fill in blank
hardFix the error in the loop condition to avoid out-of-bound access.
DSA C++
for (int i = 0; i [1] s.length() - 1; i++) { int current = value(s[i]); int next = value(s[i + 1]); if (current < next) { result -= current; } else { result += current; } } result += value(s[s.length() - 1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes out-of-bound access.
Using > or >= causes the loop to never run.
✗ Incorrect
The loop should run while i is less than s.length() - 1 to safely access s[i + 1].
4fill in blank
hardFill both blanks to correctly add or subtract values based on Roman numeral rules.
DSA C++
if (current [1] next) { result [2]= current; } else { result += current; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses the logic.
Using '+=' in subtraction case causes wrong result.
✗ Incorrect
If current is less than next, subtract current from result; otherwise, add it.
5fill in blank
hardFill all three blanks to complete the function that converts Roman numerals to integers.
DSA C++
int romanToInt(string s) {
int result = [1];
for (int i = 0; i [2] s.length() - 1; i++) {
int current = value(s[i]);
int next = value(s[i + 1]);
if (current [3] next) {
result -= current;
} else {
result += current;
}
}
result += value(s[s.length() - 1]);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting result at 1 or other values.
Using <= in loop condition causes errors.
Using > instead of < in comparison.
✗ Incorrect
Initialize result to 0, loop while i < length - 1, and subtract when current < next.
