Tuesday, June 3, 2014

LeetCode Integer to Roman

public String intToRoman(int num) {
        int[] numbers = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
       
        String result = "";
        int index = 0;
        while (num>0) {
            int times = num / numbers[index];
            num -= numbers[index] * times;
            while (times > 0) {
                result += symbols[index];
                times--;
            }
            index++;
        }
        return result;
    }

No comments:

Post a Comment