《leetCode》:Integer to Roman

来源:互联网 发布:用友软件服务合同 编辑:程序博客网 时间:2024/05/29 03:12

Given an integer, convert it to a roman numeral.

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

其中每两个阶段的之间有一个减法的表示,比如900=CM, C写在M前面表示M-C。

范围给到3999,感觉情况不多直接打表其实更快,用代码判断表示估计比较繁琐。

然后就是贪心的做法,每次选择能表示的最大值,把对应的字符串连起来。 

public class Solution {
public String intToRoman(int num) {

    int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};    String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};        StringBuilder sb = new StringBuilder();        for(int i=0;i<values.length;i++) {        while(num >= values[i]) {            num -= values[i];            sb.append(strs[i]);        }    }    return sb.toString();}

}

refrence:http://blog.csdn.net/havenoidea/article/details/11848921
原创粉丝点击