题目描述:
Given a roman numeral, convert it to an integer.
The answer is guaranteed to be within the range from 1 to 3999.
Clarification
Example
题目思路:
IV
-> 4
XII
-> 12
XXI
-> 21
XCIX
-> 99
这题需要知道单个roman到int的mapping。知道之后,发现roman number也是从个位数开始看的,看的时候顺带看前一位。如果前一位比当前位的数字小,就意味着减法(当前位-前一位);否则,就是正常的数字相加。
Mycode(AC = 18ms):
class Solution {
public:
/**
* @param s Roman representation
* @return an integer
*/
int romanToInt(string& s) {
// Write your code here
int ans = 0;
// starting from tail of s:
// 1. if s[i - 1] <= s[i], then it means number = s[i] - s[i - 1]
// 2. if i == 0, last one doesn't need check item 1).
// 3. else, then add the current roman number
for (int i = s.length() - 1; i >= 0; i--) {
if (i == 0) {
ans += r2int(s[i]);
}
else {
if (r2int(s[i]) > r2int(s[i - 1])) {
ans += r2int(s[i]) - r2int(s[i - 1]);
i--;
}
else {
ans += r2int(s[i]);
}
}
}
return ans;
}
// mapping between single roman to int
int r2int(char ch) {
if (ch == 'I') {
return 1;
}
else if (ch == 'V') {
return 5;
}
else if (ch == 'X') {
return 10;
}
else if (ch == 'L') {
return 50;
}
else if (ch == 'C') {
return 100;
}
else if (ch == 'D') {
return 500;
}
else if (ch == 'M') {
return 1000;
}
else {
return 0;
}
}
};