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();
    }
    
}

 

posted @ 2016-03-22 17:22  哥布林工程师  阅读(119)  评论(0编辑  收藏  举报