LeetCode 012 Integer to Roman

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33765907/article/details/81490317

Roman numerals are represented by seven different symbols: IVXLCD and M.

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

class Solution {
    public String intToRoman(int num) {
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(new Integer(1), "I");map.put(new Integer(2), "II");map.put(new Integer(3), "III");map.put(new Integer(4), "IV");map.put(new Integer(5), "V");map.put(new Integer(6), "VI");map.put(new Integer(7), "VII");map.put(new Integer(8), "VIII");map.put(new Integer(9), "IX");
        map.put(new Integer(10), "X");map.put(new Integer(20), "XX");map.put(new Integer(30), "XXX");map.put(new Integer(40), "XL");map.put(new Integer(50), "L");map.put(new Integer(60), "LX");map.put(new Integer(70), "LXX");map.put(new Integer(80), "LXXX");map.put(new Integer(90), "XC");
        map.put(new Integer(100), "C");map.put(new Integer(200), "CC");map.put(new Integer(300), "CCC");map.put(new Integer(400), "CD");map.put(new Integer(500), "D");map.put(new Integer(600), "DC");map.put(new Integer(700), "DCC");map.put(new Integer(800), "DCCC");map.put(new Integer(900), "CM");
        map.put(new Integer(1000), "M");map.put(new Integer(2000), "MM");map.put(new Integer(3000), "MMM");

        StringBuffer sb = new StringBuffer();
        int temp = num / 1000;
        if(temp * 1000 != 0) sb.append(map.get(new Integer(temp * 1000)));
        temp = (num / 100) % 10;
        if(temp * 100 != 0) sb.append(map.get(new Integer(temp * 100)));
        temp = (num /10) % 10;
        if(temp * 10 != 0) sb.append(map.get(new Integer(temp * 10)));
        temp = num % 10;
        if(temp != 0) sb.append(map.get(new Integer(temp)));

        return sb.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33765907/article/details/81490317