【LEET-CODE】12. Integer to Roman【Medium】
来源:互联网 发布:淘宝开店怎么实名认证 编辑:程序博客网 时间:2024/05/16 18:38
Qusetion:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路:
把整数转成罗马数字,要仔细理解罗马数字的规则,如39应该对应XLI而不是IXL。
思路的话从到大到小不断整除取余,注意如果是900+,400+这类可能出现CM,CD之类倒序(M减去C)的情况,进行判定比较。
利用了递归调用本身,但是代码依然有些冗余,后续二刷时可尝试修改(负数情况也应考虑)。
但代码效率较高,32ms打败92.79%。
Code:
class Solution {public: string intToRoman(int num) { string s; for(int i = num/1000; i>0 ; i-- ){ if(i>=4) return ""; s.push_back('M'); } num = num % 1000; for(int i = num/500; i>0 ; i-- ){ if(num < 900) s.push_back('D'); else{ s.push_back('C'); s.push_back('M'); s= s + intToRoman(num-900); return s; } } num = num % 500; for(int i = num/100; i>0 ; i-- ){ if(num < 400) s.push_back('C'); else{ s.push_back('C'); s.push_back('D'); s= s + intToRoman(num-400); return s; } } num = num % 100; for(int i = num/50; i>0 ; i-- ){ if(num < 90) s.push_back('L'); else{ s.push_back('X'); s.push_back('C'); s= s + intToRoman(num-90); return s; } } num = num % 50; for(int i = num/10; i>0 ; i-- ){ if(num < 40) s.push_back('X'); else{ s.push_back('X'); s.push_back('L'); s= s + intToRoman(num-40); return s; } } num = num % 10; for(int i = num/5; i>0 ; i-- ){ if(num < 9) s.push_back('V'); else{ s.push_back('I'); s.push_back('X'); return s; } } num = num % 5; switch(num){ case 1: s.push_back('I'); break; case 2: s.push_back('I'); s.push_back('I'); break; case 3: s.push_back('I'); s.push_back('I'); s.push_back('I'); break; case 4: s.push_back('I'); s.push_back('V'); break; } return s; }};
0 0
- 【LEET-CODE】12. Integer to Roman【Medium】
- [leet code] Roman to Integer
- [leet code] Integer to Roman
- 12. Integer to Roman Medium
- Leetcode 12. Integer to Roman (Medium) (cpp)
- Leet Code 12 & 13 Integer <---> Roman
- 题解——Leetcode 12. Integer to Roman 难度:Medium
- 【LeetCode】(12)Integer to Roman(Medium)
- LeetCode-12-Integer to Roman(哈希)-Medium
- Leetcode OJ 12 Integer to Roman [Medium]
- CODE 118: Roman to Integer
- CODE 119: Integer to Roman
- Leet Code 8 String to Integer (atoi)
- 12.Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- jstl简单应用list
- Notification
- android 动画 属性动画 ObjectAnimator
- Android Studio查看应用签名文件,SHA1值
- 有关内存分布
- 【LEET-CODE】12. Integer to Roman【Medium】
- 总结
- FFMPEG在VS2010环境下编译及若干问题的解决方案
- MD5 C语言16位和32位版本
- java的线程生命周期
- poj 3660 Cow Contest(传递闭包floyed算法)
- 1549 水王争霸
- Linux Redis-Cluster集群搭建与使用
- 发现一个特别小巧的jquery插件可以在选择的时候显示小图