#12 Integer to Roman

Description

tags: Math, String

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000


 * Example 1:
 * 
 * 
 * Input: 3
 * Output: "III"
 * 
 * Example 2:
 * 
 * 
 * Input: 4
 * Output: "IV"
 * 
 * Example 3:
 * 
 * 
 * Input: 9
 * Output: "IX"
 * 
 * Example 4:
 * 
 * 
 * Input: 58
 * Output: "LVIII"
 * Explanation: L = 50, V = 5, III = 3.
 * 
 * 
 * Example 5:
 * 
 * 
 * Input: 1994
 * Output: "MCMXCIV"
 * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Solution

class Solution {
public:
    string intToRoman(int num) {
        // 1 <= num <= 3999
        string res;
        string roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int digit[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        for (int i=0; num != 0; i++) {
            while (num >= digit[i]) {
                res += roman[i];
                num -= digit[i];
            }
        }
        return res;      
    }
};

Analysis

  • Time complexity: O(m)
  • Space complexity: O(m)
    m is the number of bits.

Points

  1. 数字位数的处理: 以往处理一个数每位,总是先去计算位数,通过繁杂的取余和除去拿到每一位的数。这个solution中用了巧妙的转换,化解了这个问题。注意这个for循环。当不方便从num入手取每一位时,转换为从和num的每一位比较的标准数入手的方式。
  2. 也不需要用到map等,处理得很简洁。采用一个string数组和一个int数组,index相互对应。

你可能感兴趣的:(#12 Integer to Roman)