Topic given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999. Train of thought first, learn Roman numerals, reference Roman numerals Roman numerals are the oldest representation of numbers, more than 2000 years earlier than Arab arrays, and originate from Rome numbers as follows Symbol:
Basic characters |
I |
V |
X |
L |
C |
D |
M |
corresponding Arabic numerals |
1 |
5 |
10 |
50 |
100 |
500 |
1000 |
Count rule:
- The same number ligatures, the number represented is equal to the number that these numbers are added to, for example: III = 3
- The small number is to the right of the large number, and the number represented is equal to the number added to the number, for example: VIII = 8
- Small numbers, limited to (I, X, and C) to the left of large numbers, represented by numbers equal to large numbers minus decimals, for example: IV = 4
- In normal use, no more than three consecutive digits must be repeated.
- Draw a line on the top of a number, indicating that the number is enlarged by 1000 times times (the subject only takes into account 3999 or less, so this rule is not used)
Secondly, Roman numerals to Arabic numerals (within 3999): The Roman numerals are traversed backwards, and if a number is smaller than the previous one, the number is added. Conversely, subtract twice times the previous number and then add the number JS code:
varRomantoint =function(s) {vararray=[]; for(vari=0;i<s.length;i++){ varWord=s.substring (i,i+1); Switch(word) { Case"I": Array[i]=1; Break; CaseV: Array[i]=5; Break; CaseX: Array[i]=10; Break; CaseL: Array[i]=50; Break; CaseC: Array[i]=100; Break; CaseD: Array[i]=500; Break; CaseM: Array[i]=1000; Break; } } varResult=array[0]; for(varj=0;j< (array.length-1); J + +){ if(array[j+1]>Array[j]) {Result+ = (array[j+1]-array[j]*2) }Else{result+=array[j+1]; } } returnresult; };
[Leetcode] Roman to Integer