[leetcode] 12. Integer to Roman 解题报告

题目链接: https://leetcode.com/problems/integer-to-roman/

Given an integer, convert it to a roman numeral.

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


思路: 

罗马数字有如下符号:
Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000)
计数规则:
(1).若干相同数字连写表示的数是这些罗马数字的和,如III=3;
(2).小数字在大数字前面表示的数是用大数字减去小数字,如IV=4;
(3).小数字在大数字后面表示的数是用大数字加上小数字,如VI=6;
组合规则:
(1)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
(2)不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
(3)V 和 X 左边的小数字只能用Ⅰ。
(4)L 和 C 左边的小数字只能用×。
(5)D 和 M 左 边的小数字只能用 C 。


为了方便计算我们将所有需要相减的数也作为基本数来做一个映射:

vector<int> numbers{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
vector<string> romans{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

这样对于一个数num, 如果num >= numbers[i], 那么就在结果中添加romans[i], 并且num = num - numbers[i], 直到num=0;

代码如下:

class Solution {
public:
    string intToRoman(int num) {
        vector<int> numbers{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        vector<string> romans{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        string result;
        int i = 0;
        while(i < romans.size())
        {
            if(num >= numbers[i])
            {
                result += romans[i];
                num -= numbers[i];
            }
            else i++;
        }
        return result;
    }
};
参考: http://www.daxueit.com/article/3618.html

你可能感兴趣的:(LeetCode,String)