https://leetcode.com/problems/roman-to-integer/
-----------------------------------------------------
1. How to read a Roman numbers? Please refer to following link:
http://4thgradecrocs.weebly.com/roman-numerals.html
I=1 V=5 X=10 L=50 C=100 D=500 M=1000
2. Basic idea is to read from right to left and :
if left one is >= the right one, use +
if left one is < the right one, use -
/////////////////////////////////////////////////////////////////////
//code 36ms
class Solution {
private:
int r2n(char c){
int res;
switch (c){
case 'I': res = 1; break;
case 'V': res = 5; break;
case 'X': res = 10; break;
case 'L': res = 50; break;
case 'C': res = 100; break;
case 'D': res = 500; break;
case 'M': res = 1000; break;
default:;
}
return res;
}
public:
int romanToInt(string s) {
int n = s.size(), res = r2n(s[n - 1]);
//read from right to left
for (int i = n - 2; i>-1; i--){
if (r2n(s[i + 1]) <= r2n(s[i]))res = res + r2n(s[i]);
else res = res - r2n(s[i]);
}
return res;
}
};
No comments:
Post a Comment