Sunday, February 24, 2013

[LeetCode] Integer To Roman

Thought:
Using a HashMap to store the relation between integer and Roman numerical.
It is really tricky that putting 4,9,40,90,400,900 into this map will result in an easier solution.

Code:
public class Solution {
    public String intToRoman(int num) {
       
        HashMap<Integer, String> roman = new HashMap<Integer, String>();
        int[] base = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
       
        roman.put(1, "I");
        roman.put(4, "IV");
        roman.put(5, "V");
        roman.put(9, "IX");
        roman.put(10, "X");
        roman.put(40, "XL");
        roman.put(50, "L");
        roman.put(90, "XC");
        roman.put(100, "C");
        roman.put(400, "CD");
        roman.put(500, "D");
        roman.put(900, "CM");
        roman.put(1000, "M");
       
        String result = new String();
        for( int temp : base ){
            while( num >= temp ){
                result = result + roman.get(temp);
                num = num - temp;
            }
        }
        return result;       
    }

}

2nd Round:
public class Solution {
    public String intToRoman(int num) {
        Map<Integer, String> dict = new HashMap<Integer, String>();
        dict.put(1, "I");
        dict.put(4, "IV");
        dict.put(5, "V");
        dict.put(9, "IX");
        dict.put(10, "X");
        dict.put(40, "XL");
        dict.put(50, "L");
        dict.put(90, "XC");
        dict.put(100, "C");
        dict.put(400, "CD");
        dict.put(500, "D");
        dict.put(900, "CM");
        dict.put(1000, "M");
        int[] key = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
        StringBuilder sb = new StringBuilder();
        int index = key.length - 1;
        while (num > 0) {
            while (num >= key[index]) {
                sb.append(dict.get(key[index]));
                num -= key[index];
            }
            index--;
        }
        return sb.toString();
    }

}

No comments:

Post a Comment