Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Converting Roman numerals to Arabic numerals corresponds to the conversion table as follows:
Single digit example I, 1 "II, 2" III, 3 "IV, 4" V, 5 "VI, 6" VII, 7 "viii,8" IX, 9 • 10-digit example X, 10 "XI, 11" XII, 12 "XIII, 13" XIV, 14 " XV, 15 "XVI, 16" XVII, 17 "XVIII, 18" XIX, 19 "XX, 20" XXI, 21 "XXII, 22" XXIX, 29 "XXX, 30" XXXIV, 34 "XXXV, 35" XXXI X, 39 "XL, 40" L, 50 "LI, 51" LV, 55 "LX, 60" LXV, 65 "LXXX, 80" XC, 90 "XCIII, 93" XCV, 95 "XCVIII, 98" XCIX, 99 "• Number of hundred examples C , 100 "CC, 200" CCC, 300 "CD, 400" D, 500 "dc,600" DCC, 700 "DCCC, 800" CM, 900 "cmxcix,999" • Thousands of examples M, 1000 "MC, 1100" MCD , 1400 "MD, 1500" MDC, 1600 "MDCLXVI, 1666" Mdccclxxxviii, 1888 "Mdcccxcix, 1899" MCM, 1900 "MCMLXXVI, 1976" MCMLXXXIV, 19 84 "MCMXC, 1990" MM, 2000 "Mmmcmxcix, 3999"
It can be seen that the basic numbers have I V X L C D M respectively corresponding to 1 5 10 50 100 500 1000 The current face of the letter is less than the following letter, such as IV indicates that the V-i current polygon number is greater than the following number, such as VI means v+i according to this can traverse s to find the value code as follows:
public class Solution {public int romantoint (String s) { int res=0;int prev=getromanvalue (s.charat (0)); res+= prev;for (int i=1;i<s.length (); i++) {int Curv=getromanvalue (S.charat (i)); if (Curv<=prev) {res+=curv;;} Else{res+=curv-2*prev;} PREV=CURV;} return res; } public int Getromanvalue (char c) { switch (c) {case ' I ': return 1; Case ' V ': return 5; Case ' X ': return ten; Case ' L ': return; Case ' C ': return; Case ' D ': return; Case ' M ': return; Default:return 0;}}}
Java-roman to Integer