LeetCode integer to Roman numeral-C# greedy algorithm

code ideas

Focus on the local optimal solution, find a way to use the special numbers corresponding to Roman numerals step by step, and finally get the result.


code

public string IntToRoman(int num)
{
        int[] values = new int[13] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
	string[] symbols = new string[13] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
 
	StringBuilder sb = new StringBuilder();
 
	int i = 0;
	while (i < 13)
	{
            if(num>=values[i])//假如大于等于特殊数字
            {
               sb.Append(symbols[i]);//添加特殊数字
               num-=values[i];
            }
            else
            {
               i++;
             }                    
                
	}
 
	return sb.ToString();
}

Guess you like

Origin blog.csdn.net/aa989111337/article/details/126455506