Playing Hacks and Stuffs!
The key intuition lies in the fact that in Roman Numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition.
m
is created and initialized with mappings between Roman numeral characters and their corresponding integer values. For example, 'I'
is mapped to 1
, 'V'
to 5
, 'X'
to 10
, and so on.ans
is initialized to 0
. This variable will accumulate the final integer value of the Roman numeral string.s
.
IX
as the test casei
is 0
, the current character s[i]
is 'I'
. Since there is a next character ('X')
, and the value of 'I'
(1)
is less than the value of 'X' (10)
, the condition m[s[i]] < m[s[i+1]]
is true. In this case, we subtract the value of the current character from ans. ans -= m[s[i]];
ans -= m['I'];
ans -= 1;
ans becomes -1.
i
is 1
, the current character s[i]
is 'X'
. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don’t need to evaluate the condition. In this case, we add the value of the current character to ans. ans += m[s[i]];
ans += m['X'];
ans += 10;
ans becomes 9.
##### Taking XI
as the test case
i
is 0
, the current character s[i]
is ‘X’. Since there is a next character (‘I’), and the value of ‘X’ (10) is greater than the value of ‘I’ (1), the condition m[s[i]] < m[s[i+1]]
is false. In this case, we add the value of the current character to ans. ans += m[s[i]];
ans += m['X'];
ans += 10;
ans becomes 10.
i
is 1, the current character s[i]
is ‘I’. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don’t need to evaluate the condition. In this case, we add the value of the current character to ans. ans += m[s[i]];
ans += m['I'];
ans += 1;
ans becomes 11.
Solve Script: link