Generic code to handle any length of integer


  • 0
    A

    It will be simple to update the mapping to extend to any length of integer

    public class Solution {
        private Dictionary<int, char> mapping = new Dictionary<int, char>(){
        {1, 'I'},{5,'V'},{10,'X'},{50,'L'},{100,'C'},{500,'D'},{1000,'M'} };  // Update if need to extend
        private arr = new[] { 1000, 100, 10, 1 }; // Update if need to extend
        public string IntToRoman(int num)
        {
            var result = "";
            if (num == 0) { return result; }
            var counter = 0;
            while (num / arr[counter] == 0) counter++;
            var r = num / arr[counter];
            if (r < 4) { result = new string(mapping[arr[counter]], r); }
            else if (r == 4) { result = mapping[arr[counter]].ToString() + mapping[arr[counter] * 5].ToString(); }
            else if (r <= 8) { result = mapping[arr[counter] * 5].ToString() + new string(mapping[arr[counter]], r - 5); }
            else { result = mapping[arr[counter]].ToString() + mapping[arr[counter] * 10].ToString(); }
            return result + IntToRoman(num - r * arr[counter]);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.