DDSA
Advertisement

12. Integer to Roman

Time: O(1)
Space: O(1)

Approach

Greedy with sorted value/symbol pairs. Repeatedly subtract the largest value that fits and append its corresponding symbol.

12.cs
C#
// Approach: Greedy with sorted value/symbol pairs. Repeatedly subtract the
// largest value that fits and append its corresponding symbol.
// Time: O(1) Space: O(1)

public class Solution
{
    public string IntToRoman(int num)
    {
        int[] values = { 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" };

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < values.Length; i++)
        {
            if (num == 0)
                break;

            while (num >= values[i])
            {
                num -= values[i];
                sb.Append(symbols[i]);
            }
        }

        return sb.ToString();
    }
}
Advertisement
Was this solution helpful?