*[lintcode] 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.

分析:前提先掌握罗马数字规律。我们将3999一下可能代表数字的所有罗马字母放入数组,从高到低依次去除n。注意900,400,90,40,9,4由于涉及到变位,为了简化算法,直接将这几个数字对应的字母也放入数组。


public class Solution {
    /**
     * @param n The integer
     * @return Roman representation
     */
    public String intToRoman(int n) {
        // I           1  
        // V           5  
        // X           10  
        // L           50  
        // C           100  
        // D           500  
        // M           1000  
          
        int[] numbers = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};  
        String[] letters = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};  
        String result ="";  
        for(int i = 0; i < 13; i++){  
            if(n >= numbers[i]){  
                int count = n / numbers[i];  
                n = n % numbers[i];  
                for(int j = 0; j < count; j++){  
                    result += letters[i];  
                }  
            }  
        }  
        return result; 
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值