[leetcode] 12. Integer to Roman 解题报告
来源:互联网 发布:如何在淘宝上买到好茶 编辑:程序博客网 时间:2024/05/27 20:03
题目链接: 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.
思路:
罗马数字有如下符号:
Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000)
计数规则:
(1).若干相同数字连写表示的数是这些罗马数字的和,如III=3;
(2).小数字在大数字前面表示的数是用大数字减去小数字,如IV=4;
(3).小数字在大数字后面表示的数是用大数字加上小数字,如VI=6;
组合规则:
(1)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
(2)不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
(3)V 和 X 左边的小数字只能用Ⅰ。
(4)L 和 C 左边的小数字只能用×。
(5)D 和 M 左 边的小数字只能用 C 。
为了方便计算我们将所有需要相减的数也作为基本数来做一个映射:
vector<int> numbers{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
vector<string> romans{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
这样对于一个数num, 如果num >= numbers[i], 那么就在结果中添加romans[i], 并且num = num - numbers[i], 直到num=0;
代码如下:
class Solution {public: string intToRoman(int num) { vector<int> nums{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector<string> roman{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int k = 0; string result; while(num > 0) { if(num >= nums[k]) { result += roman[k]; num -= nums[k]; } else k++; } return result; }};参考: http://www.daxueit.com/article/3618.html
- [leetcode] 12. Integer to Roman 解题报告
- LeetCode 12. Integer to Roman 解题报告
- [Leetcode] 12. Integer to Roman 解题报告
- 【LeetCode】Integer to Roman 和 Roman to Integer 解题报告
- 【LeetCode】Integer to Roman 和 Roman to Integer 解题报告
- [LeetCode]Roman to Integer,解题报告
- [LeetCode]Integer to Roman,解题报告
- LeetCode解题报告--Integer to Roman
- LeetCode解题报告--Roman to Integer
- 【LeetCode】Roman to Integer 解题报告
- 【LeetCode】Integer to Roman 解题报告
- [leetcode] 13. Roman to Integer 解题报告
- [LeetCode] Integer to Roman 解题报告
- [LeetCode] Roman To Integer 解题报告
- LeetCode 13. Roman to Integer 解题报告
- [Leetcode] 13. Roman to Integer 解题报告
- [LeetCode] Integer to Roman 解题报告
- [LeetCode] Roman to Integer 解题报告
- Spark On YARN自动调整Executor数量配置 - Dynamic Resource Allocation
- python脚本监控进程,服务停止后自动启动
- bzoj3524: [Poi2014]Couriers
- 持续集成回顾暨点滴分享[5] – 吐槽篇,代码提交记录很重要!
- 怎样对ZBrush中的材料进行渲染和着色
- [leetcode] 12. Integer to Roman 解题报告
- 练习二 1026 神奇的九宫格问题
- 树莓派学习系列1----选择和启动
- 使能android /system 文件夹为可读写
- sizeof详解 -- C++
- 正则 密码 由数字和字母组成, 并且不能为纯字母或纯数字
- Java模板引擎
- 设计模式-观察者模式Observer
- 【Linux】ifconfig命令详解