您的位置:首页 > 其它

LeetCode 12. Integer to Roman

2016-04-14 16:27 375 查看
题目链接: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.
题目分析:简单粗暴的打表,然后从高到低遍历num的每个位,找出对应的字符串append到结果中去。

class Solution {
public:
string intToRoman(int num) {
if(num < 1 || num > 3999)
return "";
string m[][10] = {
{"", "M", "MM", "MMM"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
};
string str = "";
for(int i = 0, base = 1000; i < 4; ++i) {
str += m[i][num/base];
num %= base;
base /= 10;
}

return str;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: