Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
The Roman numerals have the following symbols:
Rome character: I V x L C D m corresponding number: 1 5 10 50 100 500 1000 counting rule:
- If the numbers are the same, the numbers are equal to the total number of the numbers, for example, III = 3.
- A small number is on the right of a large number, and the number is equal to the sum of the numbers, for example, VIII = 8.
- A small number is limited to (I, X, and c) on the left side of a large number. The number is equal to a large number minus the number of decimal places. For example: IV = 4
- During normal use, the number must be repeated no more than three times.
- Draw a horizontal line on a number, indicating that the number is increased by 1000 times (this question only considers the number within 3999, so this rule is not used)
Idea: traverse from the front to the back. If the current number is greater than the last number, the sum is added. If the current number (I, X, c) is smaller than the last number, the number is subtracted from the sum.
This article references: 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 };
Leetcode: Roman to integer