Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
---------------------------
first, setup a dictionary, then walk through the whole string
according to the Roman numeral rule, if str[i] < str[i+1], then str[i] should be negative
watch out for the end element of the string, it could be compared to an unknown value.
class Solution {
public:
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unordered_map<char,int> k;
k['I'] = 1;
k['V'] = 5;
k['X'] = 10;
k['L'] = 50;
k['C'] = 100;
k['D'] = 500;
k['M'] = 1000;
int sum=0;
for (int i=0;i<s.length();i++) {
int sign = 1;
if (k[s[i]] < k[s[i+1]]) {
sign = -1;
}
sum = sum + k[s[i]] * sign;
}
return sum;
}
};
Added on Sep-02-2014Handled final char in string
class Solution {
public:
unordered_map<char,int> populateMap() {
unordered_map<char,int> dic;
dic['I'] = 1;
dic['V'] = 5;
dic['X'] = 10;
dic['L'] = 50;
dic['C'] = 100;
dic['D'] = 500;
dic['M'] = 1000;
dic['e'] = 0;
return dic;
}
int romanToInt(string s) {
unordered_map<char,int> dic = populateMap();
int ret = 0;
s += 'e';
for (int i = 0; i < s.length(); i++) {
if (dic[s[i]] < dic[s[i + 1]]) {
ret += dic[s[i + 1]] - dic[s[i]];
i++;
}else {
ret += dic[s[i]];
}
}
return ret;
}
};
No comments:
Post a Comment