[LintCode] Integer to Roman 整数转化成罗马数字

Given an integer, convert it to a roman numeral.

The number is guaranteed to be within the range from 1 to 3999.

Example

4 -> IV

12 -> XII

21 -> XXI

99 -> XCIX

more examples at: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

LeetCode上的原题,请参见我之前的博客Integer to Roman

解法一:

class Solution {
public:
    /**
     * @param n The integer
     * @return Roman representation
     */
    string intToRoman(int n) {
        string res = "";
        vector<vector<string>> v {{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, {"M", "MM", "MMM"}};
        int cnt = 1000;
        for (int i = 3; i >= 0; --i) {
            int t = n / cnt;
            if (t) res += v[i][t - 1];
            n %= cnt;
            cnt /= 10;
        }
        return res;
    }
};

解法二:

class Solution {
public:
    /**
     * @param n The integer
     * @return Roman representation
     */
    string intToRoman(int n) {
        string res = "";
        vector<int> val {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        vector<string> str{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        for (int i = 0; i < val.size(); ++i) {
            while (n >= val[i]) {
                n -= val[i];
                res += str[i];
            }   
        }
        return res;
    }
};

解法三:

class Solution {
public:
    /**
     * @param n The integer
     * @return Roman representation
     */
    string intToRoman(int n) {
        string res = "";
        vector<string> v1 {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        vector<string> v2 {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        vector<string> v3 {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        vector<string> v4 {"", "M", "MM", "MMM"};
        return v4[n / 1000] + v3[(n % 1000) / 100] + v2[(n % 100) / 10] + v1[n % 10];
    }
};

本文转自博客园Grandyang的博客,原文链接:整数转化成罗马数字[LintCode] Integer to Roman ,如需转载请自行联系原博主。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值