Roman numerals is represented by seven different symbols:,,,, I
V
, and X
L
C
D
M
.
Symbol valuei 1V 5X 10L 50C 100D 500M 1000
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" Output:3
Example 2:
Input: "IV" Output:4
Example 3:
Input: "IX" Output:9
Example 4:
Input: "LVIII" output:58explanation:l = v= 5, III = 3.
Example 5:
Input: "MCMXCIV" output:1994explanation:m = +, CM =/-, XC = all and IV = 4.
//time:o (n), Space:o (1)
Note: Since I stop is in the penultimate position, I jump out of the loop and add the last one
Public intRomantoint (String s) {if(s = =NULL|| S.length () = = 0) { return0; } intresult = 0; for(inti = 0; I <s.length ()-1; i++) { intCur =Map (S.charat (i)); intNext = Map (S.charat (i + 1))); if(cur >=next) {Result+=cur; } Else{ result -= cur; } } returnResult +Map (S.charat (S.length ()-1)); } Private intMapCharc) {Switch(c) { Case' I ' : return1; CaseV : return5; CaseX : return10; CaseL : return50; CaseC : return100; CaseD : return500; CaseM : return1000; default: return0; } }
Roman to Integer