Simple java solution using hasmap and single for loop


#1

public class Solution {
public int romanToInt(String A) {
HashMap<String,Integer> hm=new HashMap<String,Integer>();
hm.put(“I”,1);
hm.put(“V”,5);
hm.put(“X”,10);
hm.put(“L”,50);
hm.put(“C”,100);
hm.put(“D”,500);
hm.put(“M”,1000);
int num=0;
String str="";
for(int i=0;i<A.length();i++)
{
int x=hm.get(A.substring(i,i+1));
// System.out.print(“x=”+x+“i=”+i);
if(i+1<A.length() && hm.get(A.substring(i+1,i+2))>x)
{
int y=hm.get(A.substring(i+1,i+2));
num=num+y-x;
// System.out.print(“num=”+num+“y=”+y);
i++;
continue;
}
num=num+x;
}
// System.out.println(num);
return num;

}

}