LeetCode刷题记39-12. 整数转罗马数字

LeetCode刷题记39

12. 整数转罗马数字

题目
LeetCode刷题记39-12. 整数转罗马数字_第1张图片

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

说是中等题,其实是个简单题

39/150

你可能感兴趣的:(leetcode)