Tuesday, March 2, 2021

Integer to Roman

Problem: Convert a integer to its roman numerals. Here are the symbols that Roman numerals:

M - 1000

D - 500

C - 100

L - 50

X - 10

V - 5

I - 1

Example:

Input: num = 24
Output: "XXIV"


Approach: We have seen in the previous problem of converting roman into integer that the problem happens when next character is greater than the current character. Like "IV" or "XL" or "XC". That's why we will maintain such patterns also in our hash to solve this problem. 


Implementation in C#:

    public string IntToRoman(int num) 

    {

        string[] romanSymbols = new string[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

        int[] values = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        StringBuilder romanStringBuilder = new StringBuilder();

        for (int i = 0; i < values.Length && num > 0; ++i)

        {

            while (values[i] <= num)

            {

                num -= values[i];

                romanStringBuilder.Append(romanSymbols[i]);

            }

        }

        return romanStringBuilder.ToString();

    }


Complexity: O(nlogn)

No comments:

Post a Comment