LeetCode 012 Integer to Roman

题目描述:Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

罗马数字的计数方法:

基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
 

1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;

2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;

3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;

4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)

5、在一个数的上面画一条横线,表示这个数扩大1000倍。

如今我们最常见的罗马数字就是钟表的表盘符号:Ⅰ,Ⅱ,Ⅲ,Ⅳ(IIII),Ⅴ,Ⅵ,Ⅶ,Ⅷ,Ⅸ,Ⅹ,Ⅺ,Ⅻ……

 

Four characters are avoided being repeated in succession (such as IIII). Instead, thesymbol I could appear before V and X to signify 4 (IV) and 9 (IX) respectively. Using thesame pattern, we observe that X could appear before L and C to signify 40 (XL) and 90 (XC) respectively. The same pattern could be applied to C that is placed before D and M.

With our understanding of roman numerals, we have to decide how to extract the digitsfrom the integer. Should we extract from right to left (from the least significant digit) orfrom left to right (from the most significant digit)?

If digits are extracted from right to left, we have to append the symbols in reversed order.Extracting digits from left to right seem more natural. It is also slightly trickier but not ifwe know the maximum number of digits could the number have in advanced, which wedo – The number is within the range from 1 to 3999.

Using the additive notation, we convert to roman numerals by breaking it so each chunk can be represented by the symbol entity. For example, 11 = 10 + 1 = “X” + “I”. Similarly, 6 = 5 + 1 = “V” + “I”. Let’s take a look of an example which uses the subtractive notation: 49 = 40 + 9 = “XL” + “IX”. Note that we treat “XL” and “IX” as one single entity to avoid dealing with these special cases to greatly simplify the code.

代码如下:

class Solution {
public:
    string intToRoman(int num) {
        
        const int values[] = {
            1000,   900,    500,    400,
            100,    90,     50,     40,
            10,     9,      5,      4,
            1
        };
        
        const string symbol[] = {
            "M",    "CM",   "D",    "CD",
            "C",    "XC",   "L",    "XL",
            "X",    "IX",   "V",    "IV", 
            "I"
        };
        
        string roman;
        for(int i = 0; num > 0; i++){
            int count = num / values[i];
            num %= values[i];
            for(; count > 0; count--)
                roman += symbol[i];
        }
        
        return roman;
        
    }
};
原文地址:https://www.cnblogs.com/510602159-Yano/p/4278807.html