LeetCode 12. Integer to Roman
来源:互联网 发布:中国移动宽带网络电视 编辑:程序博客网 时间:2024/05/18 07:20
描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析
整数转换为罗马数字。
此题因为题目中明确了范围1到3999,所以用每位对应一个数组的方式较为简单。
附罗马数字的规则:
罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。
1、重复数次:一个罗马数字重复几次,就表示这个数的几倍。
2、右加左减:
2.1 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
2.2 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
2.3 左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
2.4 但是,左减时不可跨越一个位数。比如,99不可以用IC(100 - 1)表示,而是用XCIX([100 - 10] + [10 - 1])表示。(等同于阿拉伯数字每位数字分别表示。)
2.5 左减数字必须为一位,比如8写成VIII,而非IIX。
2.6 右加数字不可连续超过三位,比如14写成XIV,而非XIIII。(见下方“数码限制”一项。)
3、加线乘千:
3.1 在罗马数字的上方加上一条横线或者加上下标的Ⅿ,表示将这个数乘以1000,即是原数的1000倍。
3.2 同理,如果上方有两条横线,即是原数的1000000(1000^{2})倍。
4、数码限制:
4.1 同一数码最多只能出现三次,如40不可表示为XXXX,而要表示为XL。
4.2 例外:由于IV是古罗马神话主神朱庇特(即IVPITER,古罗马字母里没有J和U)的首字,因此有时用IIII代替Ⅳ。
代码
class Solution {public: string intToRoman(int num) { const int radix[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string roman; for (size_t i = 0; num > 0; ++i) { int count = num / radix[i]; num %= radix[i]; for (; count > 0; --count) roman += symbol[i]; } return 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
- [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
- leetcode 12. Integer to Roman
- 【leetcode】12. Integer to Roman
- Leetcode-12. Integer to Roman
- 解密ThreadLocal
- Thinking in java 集合容器
- 利用Android Studio将Protobuf文件生成Java文件
- ROS环境搭建(indigo)
- 搜索——Codeforces 763A
- LeetCode 12. Integer to Roman
- View的事件体系(三)
- POJ 1850 code(组合数学)
- 349. Intersection of Two Arrays*
- Linux下关闭开机自启动程序
- Linux 文件系统(部分)
- 【软件测试】UI和UE
- storm集成kafka报错org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for ...
- 金明的预算方案