integer to roman


  • 0
    S

    class Solution {
    public String intToRoman(int num) {

        LinkedHashMap<Integer,Character> hm=new LinkedHashMap<Integer,Character>();
        hm.put(1,'I');
        hm.put(5,'V');
        hm.put(10,'X');
        hm.put(50,'L');
        hm.put(100,'C');
        hm.put(500,'D');
        hm.put(1000,'M');
        int temp=num;
        int t=1;
        LinkedHashMap<Integer,Integer> digits=new LinkedHashMap<Integer,Integer>();
        while(temp>0)
        {
            
            int bit=temp%10;
            temp=temp/10;
            digits.put(t,bit);
            System.out.println(t);
            System.out.println(bit);
            t=t*10;
        }
        /*
     for (Integer key : digits.keySet()) {
            System.out.println(digits.get(key));
        }
        for(Map.Entry e:digits.entrySet())
        {
            System.out.println(e.getKey()+" "+e.getValue());
        }
        */
        int it=1;
        ArrayList<Character> re=new ArrayList<Character>();
        for(Map.Entry<Integer,Integer> e:digits.entrySet())
        {
            it=e.getKey();
            //System.out.print("iteratio"+it);
               // System.out.print("whynot here ");
               int m=e.getValue();
            if(m>5)
            {
                
                //System.out.print(" at >5 \n");
                if(m==9)
                {
                    re.add(hm.get(it*10));
                    re.add(hm.get(it));
                }
                else
                {
             for(int k=0;k<(m-5);k++)
             {
                 re.add(hm.get(it));
             }
                re.add(hm.get(it*5));
            }
            }
                else if(m==5)
                {
                    //System.out.print(" at 5 \n");
                    re.add(hm.get(it*5));
                }
    
                else if(m==4)
                {
                    //System.out.print(" at 4 \n");
                    re.add(hm.get(it*5));
                    re.add(hm.get(it));
                }
                else
            
                {
                    //System.out.print(" at <5 \n");
                for(int k=0;k<m;k++)
             {
                 Character y=new Character(hm.get(it));
                // System.out.print(y);
                 re.add(y);
             } 
            }
            }
                           
            
        
        
        //System.out.println("Contents of re: " + re);
        StringBuilder listString = new StringBuilder("");
    

    for (Character s : re)
    {
    listString.append(s);
    }

        String retu=listString.reverse().toString();
         System.out.println(retu);
        return retu;
    }
    

    }


Log in to reply
 

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