LeetCode 12 - Integer to Roman
2015-05-19 11:46
513 查看
一、问题描述
Description:Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
将一个整数用罗马数字表示法表示,大小范围限制在 1 到 3999。
二、解题报告
本题的关键是理解罗马数字表示法,见Wiki百科。罗马数字共有7个,即 I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。按照下述的规则可以表示任意正整数。需要注意的是罗马数字中没有”0”,与进位制无关。一般认为罗马数字只用来记数,而不作演算。
重复数次:一个罗马数字重复几次,就表示这个数的几倍。
右加左减:
在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
但是,左减时不可跨越一个位数。比如,99不可以用IC(100 - 1)表示,而是用XCIX([100 - 10] + [10 - 1])表示。(等同于阿拉伯数字每位数字分别表示。)
左减数字必须为一位,比如8写成VIII,而非IIX。
右加数字不可连续超过三位,比如14写成XIV,而非XIIII。
class Solution { static const string THOUS[4]; static const string HUNDS[10]; static const string TENS[10]; static const string ONES[10]; public: string intToRoman(int num) { string res; res += THOUS[num/1000]; res += HUNDS[num/100%10]; res += TENS[num/10%10]; res += ONES[num%10]; return res; } }; const string Solution::THOUS[] = {"","M","MM","MMM"}; const string Solution::HUNDS[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; const string Solution::TENS[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; const string Solution::ONES[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
LeetCode答案源代码:https://github.com/SongLee24/LeetCode
相关文章推荐
- #12 LeetCode——Integer to Roman
- Leetcode 12 Integer to Roman
- LeetCode 12. Integer to Roman
- LeetCode-12-Integer-to-Roman 无聊模拟题
- 【LeetCode】12 & 13 - Integer to Roman & Roman to Integer
- leetcode 12. Integer to Roman
- LeetCode----- 12.Integer to Roman
- 【LEETCODE】12-Integer to Roman
- LeetCode 12 Integer to Roman
- leetcode——12——Integer to Roman
- [LeetCode] 12. Integer to Roman
- LeetCode | #12 Integer to Roman
- LeetCode之12_Integer to Roman
- leetcode12 Integer to Roman
- LeetCode 12. Integer to Roman
- [leetcode-12]Integer to Roman(java)
- LeetCode12: Integer to Roman
- LeetCode-12-Integer to Roman(哈希)-Medium
- LeetCode 12. Integer to Roman
- LeetCode 12. Integer to Roman