Sunday, September 13, 2015

Integer to Roman | Leetcode

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

---

Solution: The system of roman numerals is a basic greedy algorithm. Take the next largest numeral whenever you can. Then move on to the next lower numeral.
public class Solution {
    public String intToRoman(int num) {
        StringBuilder sb = new StringBuilder();
        num = toRoman(sb, "M", num, 1000);
        num = toRoman(sb, "CM", num, 900);
        num = toRoman(sb, "D", num, 500);
        num = toRoman(sb, "CD", num, 400);
        num = toRoman(sb, "C", num, 100);
        num = toRoman(sb, "XC", num, 90);
        num = toRoman(sb, "L", num, 50);
        num = toRoman(sb, "XL", num, 40);
        num = toRoman(sb, "X", num, 10);
        num = toRoman(sb, "IX", num, 9);
        num = toRoman(sb, "V", num, 5);
        num = toRoman(sb, "IV", num, 4);
        num = toRoman(sb, "I", num, 1);
        return sb.toString();
    }
    
    private int toRoman(StringBuilder sb, String roman, int num, int value) {
        while (num >= value) {
            sb.append(roman);
            num -= value;
        }
        return num;
    }
}

No comments: