Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
The title means converting a given Roman number to an integer.
What are Roman numerals:
I, II, III, IV, V, VI, VII, VIII, IX, X .
The above Roman numerals are expressed as 1 2 3 4 5 6 7 8 9 10
in Roman numerals, the numbers corresponding to each character are the same as above, and the highest-level characters are m followed by the smallest of D as I
Rules:from right to left, encountered lower than the previous character level or the same as the character corresponding to the numeric value of the representation and accumulation as VII as 1+ 1+ 5 =7 A numeric value that corresponds to a higher than the previous character minus the character, such as IV as 5-1=4, is encountered The code is as follows:
<span style= "FONT-SIZE:18PX;" >class Solution {public:/* symbolvalue I1 V5 X10 L50 C100 D500 m1,000 *//need to be aware of Roman numerals There is subtraction, which iterates from the forward int romantoint (string s) {int result=0; To record which unit was last seen, use a number to record which unit occurred last, 1 2 3 4 5 6 7 for the first value of the I V X L C D M int last_show=0;//is 0 when the last occurrence value is less than or equal to the current value with addition, otherwise there is subtraction int cur_show; Current value for (Int. i=s.length () -1;i>=0;i--) {switch (S[i]) {case ' I ': Cur_show=1; if (cur_show>=last_show) result+=1; else result-=1; Break Case ' V ': cur_show=2; if (cur_show>=last_show) result+=5; else result-=5; Break Case ' X ': cur_show=3; if (cur_show>=last_show) result+=10; else result-=10; Break Case ' L ': cur_show=4; if (cur_show>=last_show) result+=50; else result-=50; Break Case ' C ': cur_show=5; if (cur_show>=last_show) result+=100; else result-=100; Break Case ' D ': cur_show=6; if (cur_show>=last_show) result+=500; else result-=500; Break Case ' M ': cur_show=7; if (cur_show>=last_show) result+=1000; else result-=1000; Break Default:break; } last_show=cur_show; } return result; }};</span>
Roman to Integer Leetcode