The 13th question of Leetcode
Roman numerals is represented by seven different symbols:,,,, I
V
, and X
L
C
D
M
.
Symbol Valuei 1V 5X L C D 1000M
For example, the written as in II
Roman numeral, and the just, the added together. Twelve is written as, XII
and which is simply X
+ II
. The number twenty seven XXVII
is written as and which is XX
+ V
+ II
.
Roman numerals is usually written largest to smallest from left to right. However, the numeral for four are not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, and which is written as IX
. There is six instances where subtraction is used:
I
Can be placed before V
(5) and X
(Ten) to make 4 and 9.
X
can be placed before () and (+) to make and L
C
90.
C
Can be placed before D
() and (+) to make and M
900.
Given a Roman numeral, convert it to an integer. Input is guaranteed to being within the range from 1 to 3999.
Example 1:
Input: "III"3
Example 2:
Input: "IV"4
Example 3:
Input: "IX"9
Example 4:
Input: "LVIII"= +, L = +, XXX = + and III = 3.
Example 5:
Input: "Mcmxciv"1994= +, CM =/-, XC = all and IV = 4.
Not much nonsense, directly on the code, posture must be good-looking
classSolution {Private int[] num; Public intRomantoint (String s) {//Convert roman letters to numbers firstStringtonum (s); //check left small right big caseCheckleftdigit (); //sum intsum = 0; for(intL = 0;l<num.length;l++) {sum+=Num[l]; } returnsum; } Public voidStringtonum (String s) {num=New int[S.length ()]; for(intI=0;i<s.length (); i++){ Switch(S.charat (i)) { Case' I ': Num[i]=1; Break; CaseV: Num[i]=5; Break; CaseX: Num[i]=10; Break; CaseL: Num[i]=50; Break; CaseC: Num[i]=100; Break; CaseD: Num[i]=500; Break; CaseM: Num[i]=1000; Break; default: Num[i]=0; Break; } } } Public voidCheckleftdigit () { for(intj = 0;j<num.length;j++){ for(intK = j+1;k<num.length;k++){ if(Num[j]==1 && (num[k]==5 | | num[k]==10) ) {Num[j]*= (-1); }Else if(num[j]==10 && (num[k]==50 | | num[k]==100) ) {Num[j]*= (-1); }Else if(num[j]==100 && (num[k]==500 | | num[k]==1000) ) {Num[j]*= (-1); } } } }}
1. Because it is handwriting, the API will be wrong, the length of the string is not long (), the length of the array is not size ()
2. At first I consider whether there will be IXC (109? 91? 89? The situation, later examining found that the Roman letter normal condition left big right small, moreover 109 is cix,91 is xci,89 is lxxxix; so there will be no IXC situation, you don't have to judge
3. Char can also be judged by ASCII to determine the size and difference, but in the end it will be converted to int added, so I first turned into int
"Leetcode algorithm" Roman to Integer