LeetCode OJ算法题(十二):Integer to Roman
来源:互联网 发布:js 保留字 with 编辑:程序博客网 时间:2024/05/03 17:39
题目:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解法:此题关键是阅读罗马计数的规则,下面是维基百科给出的规则
其实,我们可以总结为:对于普通数字的每一位分别来表示!
对于百位上的数字,C,CC,CCC,CD,D,DC,DCC,DCCC,CM为1——9
对于十位上的数字,X,XX,XXX,XL,L,LX,LXX,LXXX,XC 为1——9
对于个位上的数字,I,II,III,IV,V,VI,VII,VIII,IX为1——9
观察知道仅在4,9这两个数上会出现减法(即左减模式),因此对于每一位都在10,9,5,4上加以区分。
public class No12_IntegerToRoman {public static void main(String[] args){System.out.println(intToRoman(2794));}public static String intToRoman(int num) { String ret = ""; while(num != 0){ if(num >= 1000){ num -= 1000; ret += "M"; continue; } if(num >= 900){ num -= 900; ret += "CM"; continue; } if(num >= 500){ num -= 500; ret += "D"; continue; } if(num >= 400){ num -= 400; ret += "CD"; continue; } if(num >= 100){ num -= 100; ret += "C"; continue; } if(num >= 90){ num -= 90; ret += "XC"; continue; } if(num >= 50){ num -= 50; ret += "L"; continue; } if(num >= 40){ num -= 40; ret += "XL"; continue; } if(num >= 10){ num -= 10; ret += "X"; continue; } if(num >= 9){ num -= 9; ret += "IX"; continue; } if(num >= 5){ num -= 5; ret += "V"; continue; } if(num >= 4){ num -= 4; ret += "IV"; continue; } if(num >= 1){ num -= 1; ret += "I"; continue; } } return ret; }}
0 0
- LeetCode OJ算法题(十二):Integer to Roman
- LeetCode OJ算法题(十三):Roman to Integer
- LeetCode OJ:Roman to Integer
- LeetCode OJ:Integer to Roman
- LeetCode OJ - Roman to Integer
- LeetCode OJ - Integer to Roman
- [LeetCode OJ]Roman to Integer
- [LeetCode OJ]Integer to Roman
- LeetCode OJ : Roman to Integer
- LeetCode OJ Roman to Integer
- LeetCode OJ Integer to Roman
- LeetCode OJ - Integer to Roman
- LeetCode OJ - Roman to Integer
- LeetCode算法题之Roman to Integer
- <LeetCode OJ> 13 / 12 Roman to Integer & Integer to Roman
- 每日算法之十二:Roman to Integer
- LeetCode OJ 之 Roman to Integer(罗马数字转十进制)
- LeetCode OJ 12 Integer to Roman
- cocos2d-x v3.0 事件派发机制
- mysql处理添加外键时 error 150 问题
- Delphi 调用Dll
- A tool named "SQL source control"
- div强制、自动换行
- LeetCode OJ算法题(十二):Integer to Roman
- eclipse+webservice开发实例
- eclipse上的几个Velocity插件
- JavaScript中this关键字含义及其最佳实践(二)
- 【Leetcode长征系列】Populating Next Right Pointers in Each Node
- java获取url地址后缀名
- Android4.2.2 支持samba服务
- MongoDB在windows下安装教程
- USACO Section 1.2 Name That Number