Sponsored
Sponsored
This approach utilizes a greedy strategy by iterating over an ordered list of numeral values and corresponding symbols. Starting from the largest value, it repeatedly subtracts from the given number until the result is less, appending the equivalent symbol each time. This ensures the numeral is created with the fewest characters.
Time Complexity: O(1) — The solution has a fixed iteration through a constant list of length 13, hence it's O(1).
Space Complexity: O(1) — Uses constant space for the result string and numeral arrays.
1using System;
2
3public class Solution {
4 public string IntToRoman(int num) {
5 int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
6 string[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
7
8 string result = "";
9
10 for (int i = 0; i < values.Length; i++) {
11 while (num >= values[i]) {
12 result += symbols[i];
13 num -= values[i];
14 }
15 }
16
17 return result;
18 }
19
20 public static void Main(string[] args) {
21 Solution solution = new Solution();
22 int number = 1994;
23 Console.WriteLine("Roman numeral for " + number + " is " + solution.IntToRoman(number));
24 }
25}This C# implementation uses two arrays to represent numeral integers and symbols. The loop inside the main method handles the conversion, systematically assembling the Roman numeral string equivalent for the given number.