【LeetCode】Integer to Roman
来源:互联网 发布:手机3d软件 编辑:程序博客网 时间:2024/06/16 05:07
题目描述
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
题目分析
就是给出一个整数,求出罗马数字的表达示。
思路不难,做一个映射表,
mp[1] = "I"; mp[5] = "V";
mp[10] = "X"; mp[50] = "L";
mp[100] = "C"; mp[500] = "D";
mp[1000] = "M";
mp[10] = "X"; mp[50] = "L";
mp[100] = "C"; mp[500] = "D";
mp[1000] = "M";
整数后面往前判断,并记录进行到哪一位。
while(num) { tmp = num%10; switch(tmp) { case 0: break; case 1:case 2:case 3: while(tmp--)ret = mp[cmpnum] + ret; break; case 4:case 9: ret = mp[(tmp+1)*cmpnum] + ret; ret = mp[cmpnum] + ret; break; case 5: ret = mp[cmpnum*5] + ret; break; case 6:case 7:case 8: while((tmp--)-5)ret = mp[cmpnum] + ret; ret = mp[cmpnum*5] + ret; break; }cmpnum *= 10;num = num/10;}
如:3654
开始,记录一个cmpnum = 1,表示进行到个位
3654%10 = 4;
对于4,我们在结果前加一个mp[cmpnum*5]对应的值,再添加一个mp[cmpnum]代表的值,添加一个IV,此时结果是IV
循环下一次365%10=5,cmpnum = 10
对于5,我们在结果前加一个mp[cmpnum*5]对应的值就行,添加一个L,此时结果是LIV
循环下一次36%10=6,cmpnum = 100
对于6,我们在结果前加一个mp[cmpnum]对应的值,再添加一个mp[cmpnum]*5代表的值,添加一个DC,此时结果是DCLIV
循环下一次3%10=3,cmpnum = 1000
判断3,根据上面的条件,我们在结果里添加三次mp[cmpnum]代表的值就是MMM,此时结果是MMMDCLIV。
代码示例
推荐学习C++的资料
C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919
在线C++API查询
http://www.cplusplus.com/
map使用方法http://www.cplusplus.com/reference/map/map/
0 0
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- 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: Integer to Roman
- Leetcode: Roman to Integer
- LeetCode Integer to Roman
- 【leetcode】Roman to Integer
- 算法:链表的快速排序法
- 字符串包含--数组存储O(m+n)
- 8.0 Introduction(Implementing Gesture Recognizers)
- 无线USB网卡,RaspberryPi无线配置,Raspbian无线配置
- Chrome安装脚本和Chrome网上应用商店外的第三方扩展
- 【LeetCode】Integer to Roman
- Set集合解决年龄问题:年龄的4次方是个6位数。这10个数字正好包含了从0到9这10个数字,
- VMProtect SDK测试
- 算法导论——二叉查找树
- 正则表达式 整数浮点数
- rsync使用
- Windows 8.1 Update 1正式开放下载/自动更新
- mysql高级 tigger触发器 --[2]
- 优化WebLogic 服务器性能参数