Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字有如下符号:
罗马字符: I V X L C D M
对应数字: 1 5 10 50 100 500 1000
计数规则:
- 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
- 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
- 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
- 正常使用时,连续的数字重复不得超过三次
- 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)
思路:从前向后遍历,当前数字比后一个数字大则加入总和,当前数字(I,X,C)比后一个数字小则从总和中减去该数字。
本文参考了:http://blog.csdn.net/wzy_1988/article/details/17057929
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 int str[26]; 5 str['I'-'A']=1; 6 str['V'-'A']=5; 7 str['X'-'A']=10; 8 str['L'-'A']=50; 9 str['C'-'A']=100; 10 str['D'-'A']=500; 11 str['M'-'A']=1000; 12 int sum=0,n=s.size(); 13 s.push_back(s[n-1]); 14 for(int i=0;i<n;i++) 15 { 16 if(str[s[i]-'A']>=str[s[i+1]-'A']) 17 sum+=str[s[i]-'A']; 18 else if(s[i]=='I'||s[i]=='X'||s[i]=='C') 19 sum-=str[s[i]-'A']; 20 } 21 return sum; 22 } 23 };