Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Idea: Before always think the Roman numeral good trouble, a brush when see on headache do not want to do. After looking at the wiki, I feel really good. This problem directly to a valid Roman numerals, you can directly from the back to calculate, do not consider so many rules, in addition to small in the large front to use a large reduction, the others accumulate. Save the corresponding value with HashMap, then use a prev to save the next Roman numeral to compare the current.
Roman numerals ref:https://zh.wikipedia.org/wiki/%e7%bd%97%e9%a9%ac%e6%95%b0%e5%ad%97
Public classSolution { Public intRomantoint (String s) {intRes=0; Map<Character,Integer> save=NewHashmap<character,integer>(); Save.put (' I ', 1); Save.put (' V ', 5); Save.put (' X ', 10); Save.put (' L ', 50); Save.put (' C ', 100); Save.put (' D ', 500); Save.put (' M ', 1000); intPrev=0; for(intI=s.length () -1;i>=0;i--) { intCurrent=Save.get (S.charat (i)); if(current>=prev) {Res+=Current ; } Else{res-=Current ; } prev=Current ; } returnRes; }}
Roman to Integer