美文网首页leetcode-algorithm
leetcode-012 Integer to Roman

leetcode-012 Integer to Roman

作者: hylexus | 来源:发表于2016-10-03 22:28 被阅读39次

    [TOC]

    P012 Integer to Roman

    Given an integer, convert it to a roman numeral.

    Input is guaranteed to be within the range from 1 to 3999.

    思路分析

    这个和小学数学的考题类似了,比如问123是由几个100,几个10和几个1构成的?

    关键就是找出构成数字的元数字:

    二进制的元数字是0和1
    十进制的元数字是0到9

    罗马数字的元数字如下:

    罗马字符 I V X L C D M
    阿拉伯数字 1 5 10 50 100 500 1000

    将输入数字按照这种方式拆分成几个千几个百……即可。

    代码

    java

    
    public class Solution012 {
    
        public static final String[][] base = { //
                { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }, //
                { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }, //
                { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }, //
                { "", "M", "MM", "MMM" } //
        };
    
        public String intToRoman(int num) {
            StringBuilder sb = new StringBuilder();
            sb.append(base[3][(num / 1000) % 10]);
            sb.append(base[2][(num / 100) % 10]);
            sb.append(base[1][(num / 10) % 10]);
            sb.append(base[0][(num % 10)]);
            return sb.toString();
        }
    
        public static void main(String[] args) {
            Solution012 s12 = new Solution012();
            int xs[] = { 1, 4, 6, 7, 9, 18, 19, 99, 3999 };
            for (int x : xs) {
                System.out.println(x + "-->" + s12.intToRoman(x));
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:leetcode-012 Integer to Roman

        本文链接:https://www.haomeiwen.com/subject/lzyjyttx.html