Tuesday, October 16, 2012

[LeetCode] Integer to Roman

Given an integer, convert it to a roman numeral.

Java Code:
public String intToRoman(int num) {
       HashMap intRomanMap = new HashMap();
       intRomanMap.put(1000, "M");
       intRomanMap.put(900, "CM");
       intRomanMap.put(500, "D");
       intRomanMap.put(400, "CD");
       intRomanMap.put(100, "C");
       intRomanMap.put(90, "XC");
       intRomanMap.put(50, "L");
       intRomanMap.put(40, "XL");
       intRomanMap.put(10, "X");
       intRomanMap.put(9, "IX");
       intRomanMap.put(5, "V");
       intRomanMap.put(4, "IV");
       intRomanMap.put(1, "I");
       
       
       String result = "";
       int[] ints = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
       
       for(int i = 0; num > 0 && i < ints.length; i ++){
           int remainder = num/ints[i];
           num = num%ints[i];
           
           for(int j = 0; j < remainder; j++){
               result += intRomanMap.get(ints[i]);
           }         
       }
       
       return result;
       
    }

No comments:

Post a Comment