use HashMap java solution


  • 0
    Z
    public class Solution {
        public String intToRoman(int n) {
            HashMap<Integer,String> map=new HashMap<Integer,String>();
            map.put(1,"I");
            map.put(5,"V"); 
            map.put(10,"X"); 
            map.put(50,"L");
            map.put(100,"C");
            map.put(500,"D"); 
            map.put(1000,"M");
          String res="";
          int j=1000;
          while(n>0)
          {
          if(n/j>=9)
          {
              res+=map.get(1*j)+map.get(10*j);
              n=n-(n/j)*j;
          }
          if(n/j>=5)
          {
              res+=map.get(5*j);
              int i=n/j - 5;
             while(i-- >0) res+=map.get(1*j);
           n=n-(2*n/j-5)*j;
          }
          if(n/j>=4)
          {
              res+=map.get(1*j)+map.get(5*j);
              n=n-(n/j)*j;
          }
          if(n/j>=1)
          {
              int i=n/j;
             while(i-- >0) res+=map.get(j);
           n=n-(n/j)*j;
          } 
           j=j/10;
          }
          return res;
        }
    }
    

Log in to reply
 

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