Saturday, September 21, 2013

Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

Solution:
We take two arrays containing the special cases. Since the number will not be greater than 3999, we need to know the Roman representations of up to he number 1000.
M = 1000
D = 500
C = 100
L = 50
X = 10
V = 5
I = 1

Here's the code. I got it from the comments on the Leetcode's problem page. Concise and precise.

class Solution {
public:
    string intToRoman(int num) {
        string result;
        int newnum;
        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        string symbols[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        for(int i =0; i<13;i++)
        {
            newnum = num/values[i];
             num = num-newnum*values[i];
            while(newnum--)
            {
                result.append(symbols[i]);
            }
      
        }
        return result;
    }
};

No comments:

Post a Comment