[Problem]
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
[Analysis]
After creating a character-to-number map, you only need to catch two conditions: 1. The inputs are all valid Roman numerals; 2. Subtraction is required when the small number is to the left of the large number.
[Solution]
Public classSolution { Public intRomantoint (String s) {intresult = 0; for(inti = 0; I < s.length (); i++) { intCurval =Romantodigit (S.charat (i)); if(i + 1 <s.length ()) { intNextval = Romantodigit (S.charat (i + 1)); if(Nextval >curval) {Result+ = Nextval-Curval; I++; } Else{result+=Curval; } } Else{result+=Curval; } } returnresult; } Public intRomantodigit (Charc) {Switch(c) { Case' I ':return1; Case' V ':return5; Case' X ':return10; Case' L ':return50; Case' C ':return100; Case' D ':return500; Case' M ':return1000; default:return0; } }}
Leetcode #13 Roman to Integer (E)