lintcode-medium-Integer to Roman

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Integer to Roman相关的知识,希望对你有一定的参考价值。

Given an integer, convert it to a roman numeral.

The number is guaranteed to be within the range from 1 to 3999.

 

4 -> IV

12 -> XII

21 -> XXI

99 -> XCIX

 

public class Solution {
    /**
     * @param n The integer
     * @return Roman representation
     */
    public String intToRoman(int n) {
        // Write your code here
        
        if(n <= 0)
            return "";
        
        String[] strs = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
        int[] nums = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
        
        StringBuilder result = new StringBuilder();
        int index = strs.length - 1;
        
        while(n > 0){
            
            while(n >= nums[index]){
                result.append(strs[index]);
                n -= nums[index];
            }
            index--;
        }
        
        return result.toString();
    }
    
}

 

以上是关于lintcode-medium-Integer to Roman的主要内容,如果未能解决你的问题,请参考以下文章

TopN案例

Lua table直接索引VS缓存索引性能测试小示例

如何求解:T(n) = T(n/2) + T(n/4) + T(n/8) + (n)

递归的复杂度:T(n) = T(n-1) + T(n-2) + C

java <T>T和T的区别

Java之泛型<T> T与T的用法