Topic:
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Test instructions
Given a Roman number, convert it to an integer.
The given input is guaranteed to be between 1-3999
Algorithm Analysis:
* Roman Numeral rules:
* 1, a total of 7 Roman numerals, namely I (1), V (5), X (10), L (50), C (100), D (500) and M (1000).
* There is no "0" in Roman numerals.
* 2, repetition: a Roman numeral repeats up to 3 times.
* 3, right plus left minus:
* Lower Roman numerals on the right side of the larger Roman numerals, indicating large numbers plus small numbers.
* On the left of the larger Roman numerals, the smaller Roman numerals indicate that large numbers decrease the numbers.
AC Code:
public class solution{ private int sss; public int Romantoint (String s) { map<character, integer> dct=new hashmap<character, Integer > (); Dct.put (' I ', 1); Dct.put (' I ', 1); Dct.put (' V ', 5); Dct.put (' V ', 5); Dct.put (' X ', ten); Dct.put (' x ', ten); Dct.put (' L ', +); Dct.put (' l ', +); Dct.put (' C ', +); Dct.put (' C ', +); Dct.put (' D ', +); Dct.put (' d ', +); Dct.put (' M ', +); Dct.put (' m ', +); int sum = 0, J; for (int i = 0; i < s.length (); ++i) { j = i+1; if (J < s.length () && Dct.get (S.charat (j)) > Dct.get (S.charat (i))) { sum + = Dct.get (S.charat (j) )-Dct.get (S.charat (i)); i = j; } else sum + = Dct.get (S.charat (i)); } return sum; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Roman to Integer