LeeCode-Roman to Integer
4324 ワード
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Input is guaranteed to be within the range from 1 to 3999.
1 class Solution {
2 public:
3 int romanToInt(string s) {
4 int length = s.length();
5 if(length <1) return 0;
6 map<char,int> m;
7 m['I'] = 1;
8 m['V'] = 5;
9 m['X'] = 10;
10 m['L'] = 50;
11 m['C'] = 100;
12 m['D'] = 500;
13 m['M'] = 1000;
14 int i = length-1;
15 int sum = m[s[i--]];
16 while(i>=0)
17 if(m[s[i+1]] > m[s[i]])
18 sum -= m[s[i--]];
19 else
20 sum += m[s[i--]];
21 return sum;
22 }
23 };