LeetCode 12: Integer to Roman
来源:互联网 发布:淘宝怎么批量发布宝贝 编辑:程序博客网 时间:2024/04/30 12:17
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解题思路
首先需要了解罗马数字的表示规则:
罗马数字规则:
1. 罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000),罗马数字中没有“0”。
2. 重复次数:一个罗马数字最多连续重复3次。
3. 右加左减:
3.1 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字
3.2 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字
4. 左减的数字有限制,仅限于I、X、C,且只能减一个数字:
4.1 V 和 X 左边的小数字只能用Ⅰ
4.2 L 和 C 左边的小数字只能用X
4.3 D 和 M 左 边的小数字只能用C
5. 在一个数的上面画一条横线,表示这个数扩大1000倍。
采用贪心策略,每次选择能表示的最大的值,把对应的字符串连接起来;
class Solution {public: string intToRoman(int num) { string str; // Note:900, 400, 90, 40, 9, 4 string symbol[]={"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; int value[]= {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; for (int i = 0; num != 0; ++i) { while(num >= value[i]) { num -= value[i]; str += symbol[i]; } } return str; }};
0 0
- [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-12Integer 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
- 黑马程序员 Java基础——Set集合
- POP3、SMTP和IMAP之间的区别和联系
- 十进制计数器的设计
- 12.Python标准库_数学与随机数 (math包,random包)
- 沙盒操作的核心函数 - NSSearchPathForDirectoriesInDomains用法
- LeetCode 12: Integer to Roman
- 学习网站
- Nginx Location配置总结
- Surrounded Regions
- 芝诺悖论:“人永远追不上乌龟” p.s.飞箭不动悖论
- HTML5——Web Worker使用方法
- ubuntu编译内核
- 【IOS 开发学习总结-OC-58】★UI控件——UITabBar 与UITabBarController
- 在COIDE下使用uCOS-II的一些问题