Roman to Integer
https://leetcode.com/problems/roman-to-integer/
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
1 import java.util.HashMap; 2 import java.util.Map; 3 4 public class Solution { 5 public static int romanToInt(String s) { 6 Map<String,Integer>roman2int=createMap(); 7 int ans=0; 8 int start=0;int end=0; 9 int len=s.length(); 10 while(end<len){ 11 start=end;end++; 12 String t=""+s.charAt(start); 13 while(end<len&&roman2int.containsKey(t+s.charAt(end))){ 14 t+=s.charAt(end); 15 end++; 16 } 17 ans+=roman2int.get(t); 18 } 19 return ans; 20 } 21 public static Map<String,Integer> createMap(){ 22 Map<String,Integer>roman2int=new HashMap(); 23 roman2int.put("I", 1); 24 roman2int.put("II", 2); 25 roman2int.put("III", 3); 26 roman2int.put("IV", 4); 27 roman2int.put("V", 5); 28 roman2int.put("VI", 6); 29 roman2int.put("VII", 7); 30 roman2int.put("VIII", 8); 31 roman2int.put("IX", 9); 32 roman2int.put("X", 10); 33 roman2int.put("XX", 20); 34 roman2int.put("XXX", 30); 35 roman2int.put("XL", 40); 36 roman2int.put("L", 50); 37 roman2int.put("LX", 60); 38 roman2int.put("LXX", 70); 39 roman2int.put("LXXX", 80); 40 roman2int.put("XC", 90); 41 roman2int.put("C", 100); 42 roman2int.put("CC", 200); 43 roman2int.put("CCC", 300); 44 roman2int.put("CD", 400); 45 roman2int.put("D", 500); 46 roman2int.put("DC", 600); 47 roman2int.put("DCC", 700); 48 roman2int.put("DCCCC", 800); 49 roman2int.put("CM", 900); 50 roman2int.put("M", 1000); 51 roman2int.put("MM", 2000); 52 roman2int.put("MMM", 3000); 53 return roman2int; 54 } 55 public static void main(String[]args){ 56 System.out.println(romanToInt("MDLXVII")); 57 } 58 }