I think this should be marked as Easy


  • 0

    It's very easy to figure it out as soon as you understand what's Roman Number.
    And here's my common solution

        public string IntToRoman(int num) {
            string rs="";
            int[] vals = {1000, 500, 100, 50, 10, 5, 1};
            char[] chars = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
            for(int i = 0; i < vals.Length && num > 0 ; i+=2)
            {
                int cur = num / vals[i];
                if(cur == 0)
                {
                    num = num % vals[i];
                    continue;
                }
                if(cur < 4)
                {
                    while(cur > 0)
                    {
                        rs += chars[i].ToString();
                        cur--;
                    }
                }
                else if(cur == 4)
                {
                    rs += chars[i].ToString() + chars[i - 1].ToString();
                }
                else if(cur < 9)
                {
                    rs += chars[i - 1].ToString();
                    while(cur - 5 > 0)
                    {
                        rs += chars[i].ToString();
                        cur--;
                    }
                }
                else if(cur == 9)
                {
                    rs += chars[i].ToString() + chars[i - 2].ToString();
                }
                num = num % vals[i];
            }
            return rs;
        }
    

Log in to reply
 

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