Title Description:
Given a Roman numeral, convert it to an integer.
Problem Solving Ideas:
The Roman notation has the following rules:
- The basic number Ⅰ, X, C any one, the number of their own use, or put on the right side of the large number of the composition, not more than three; on the left of the large number can only be used one;
- It is not possible to use any one of the basic digits V, L, D as decimals on the left side of the large number to make up the number by subtracting the method;
- The small numbers on the left of V and X can only be used Ⅰ;
- The small numbers on the left of L and C can only be used with X;
- The small numbers on the left of D and M can only be used in C.
So only i,x,c, which may appear on the left side of the larger number than he represents. Therefore, this problem can scan the string from the beginning, when encountering {i,x,c}, look at their next position value, if greater than the number of their expression value, then subtract the current value, plus the next value, and skip scanning the next character. As for other cases, they can be added directly to the values they represent.
Specific code:
1 Public classSolution {2 Public intRomantoint (String s) {3 int[] value={1000,500,100,50,10,5,1};4 Char[] array = "MDCLXVI". ToCharArray ();5 6 intSum=0;7 for(intI=0;i<s.length (); i++){8 CharCh=S.charat (i);9 intindex=findindex (array, ch);Ten if(index==2| | index==4| | Index==6){ One if(I+1<s.length () && s.charat (i+1) = = Array[index-1]){ Asum=sum+value[index-1]-Value[index]; -i++; - } the Else if(I+1<s.length () && s.charat (i+1) = = Array[index-2]){ -sum=sum+value[index-2]-Value[index]; -i++; - } + Else{ -sum+=Value[index]; + } A } at Else{ -sum+=Value[index]; - } - } - returnsum; - } in Public Static intFindIndex (Char[] Array,Charch) { - for(inti=0;i<array.length;i++){ to if(array[i]==ch) + returni; - } the return-1; * } $}
"Leetcode" 13. Roman to Integer