[LeetCode] Roman to Integer, leetcoderoman
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
This question mainly involves figuring out the algorithm for turning Roman into Integer.
Remember that if a number is smaller than the previous one, it will be used as a plus number, and vice versa, it will be used as a reduction. (Eg: IV = 4, XLV = 45, XX = 20)
Therefore, we can start from the end of the team and slowly determine whether a number should be + or -.
The Code is as follows .~
public class Solution { public int romanToInt(String s) { if(s==null||s.length()==0){ return 0; } HashMap<Character,Integer> hash=new HashMap<Character,Integer>(); hash.put('I',1); hash.put('V',5); hash.put('X',10); hash.put('L',50); hash.put('C',100); hash.put('D',500); hash.put('M',1000); int len=s.length(); int result=hash.get(s.charAt(len-1)); int compare=result; for(int i=len-2;i>=0;i--){ int curr=hash.get(s.charAt(i)); if(curr>=compare){ result=result+curr; }else{ result=result-curr; } compare=curr; } return result; }}