Roman To Integer using HashMap Java


  • 0
    P

    To convert Roman to integer using HashMap Java

    HashMap<String,Integer> h=new HashMap<String,Integer>();
            h.put("I",1);
            h.put("IV",4);
            h.put("IX",9);
            h.put("XL",40);
            h.put("XC",90);
            h.put("CD",400);
            h.put("CM",900);
            h.put("V",5);
            h.put("X",10);
            h.put("L",50);
            h.put("C",100);
            h.put("D",500);
            h.put("M",1000);
            
            int res=0;
            String key;
            char c[]=s.toCharArray();
            for(int i=0;i<c.length;i++)
            {
                if(i<c.length-1)
                {
                key=""+c[i]+c[i+1];
                if(h.containsKey(key))
                {
                    res=res+h.get(key);
                    i++;
                }
                else
                {
                    key=""+c[i];
                    res=res+h.get(key);
                }
                }
                else
                {
                 key=""+c[i];
                    res=res+h.get(key);
       
                }
                
            }
            return res;
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.