LeetCode #12:Integer to Roman(整数转罗马数字)

题目描述:

思路:

由于保证了输入的测试数据在1-3999之间,所以我们可以将所有可能的罗马数字字符的组合存在一个字符串数组中以方便调用。

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

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注