Friday, November 7, 2014

Facebook: Integer to Roman

Integer to Roman
http://buttercola.blogspot.com/2014/09/leetcode-integer-to-roman.html
public class Solution {
    public String intToRoman(int num) {
        if (num < 1 && num > 3999) {
            return "";
        }
        
        String[] roman = new String[]{"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
        int[]    digit = new int[]{1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
        
        StringBuilder sb = new StringBuilder();
        for (int i = digit.length - 1; i >= 0; i--) {
            while (num >= digit[i]) {
                sb.append(roman[i]);
                num -= digit[i];
            }
        }
        
        return sb.toString();
    }
}

No comments:

Post a Comment