12. Integer to Roman

来源:互联网 发布:medusa 软件 编辑:程序博客网 时间:2024/05/23 02:19

Given an integer, convert it to a roman numeral.

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

Subscribe to see which companies asked this question

迭代可解

public class Solution {    private int[] val = {            1000, 900, 500, 400,            100, 90, 50, 40,            10, 9, 5, 4,            1    };    private String[] syb = new String[] {            "M", "CM", "D", "CD",            "C", "XC", "L", "XL",            "X", "IX", "V", "IV",            "I"    };    public String intToRoman(int num) {         StringBuilder roman = new StringBuilder();        int i = 0, k;        while (num > 0) {            k = num / val[i];            while (k-- > 0) {                roman.append(syb[i]);                num -= val[i];            }            i++;        }        return roman.toString();    }}


0 0
原创粉丝点击