problem
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Tags:math, String
Code
Public classSolution { Public intRomantoint (String s) {map<character, integer>Map=NewHashmap<character, integer> ();Map. put (' I ',1);Map. put (' V ',5);Map. put (' X ',Ten);Map. put (' L ', -);Map. put (' C ', -);Map. put (' D ', -);Map. put (' M ', +);intresult =0;intLen = S.length (); for(inti =0; I < Len-1; i++) {Charc = S.charat (i);intAdd =Map. get (c);Switch(c) {//Refer to the calculation rules in the following description of the article Case ' I ':if(S.charat (i +1) ==' V '|| S.charat (i +1) ==' X ') Result-= add;ElseResult + = add; Break; Case ' X ':if(S.charat (i +1) ==' L '|| S.charat (i +1) ==' C ') Result-= add;ElseResult + = add; Break; Case ' C ':if(S.charat (i +1) ==' D '|| S.charat (i +1) ==' M ') Result-= add;ElseResult + = add; Break; Case ' V ': Case ' L ': Case ' D ': Case ' M ': Result + = add; Break;default: Break; } }returnResult +Map. Get (S.charat (Len-1)); }}
Run Time
Description
The rules for the calculation of Roman numerals refer to the following points:
Basic characters
(' I ', 1) (' V ', 5) (' X ', 10) (' L ', 50) (' C ', 100) (' D ', 500) (' M ', 1000)
1, the same number ligatures, the number represented is equal to the number of these numbers added, such as: ⅲ= 3;
2, the small number on the right side of the large number, the number represented is equal to the number of these numbers added, such as: ⅷ= 8;ⅻ= 12;
3, the small number, (limited to Ⅰ, X and C) on the left side of the large number, the number represented is equal to the number of large number reduction obtained, such as: ⅳ= 4;ⅸ= 9;
4, V and X left small numbers can only be used Ⅰ.
The small numbers on the left of 5, L and C can only be used with X.
The small numbers on the left of 6, D and M can only be used in C.
Link: Roman digital Baidu Encyclopedia
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode #13 Roman to Integer #Java