题目之前就完成了,今天补博客~
由于种种原因,以后的LeetCode刷题虽然会继续,但是对于过于简单的题,我不会再以博客的形式展现了,我会把每次做的题都提交到Github上,地址如下:GitHub地址
**题目要求:**Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
拼写规则: 罗马数字的拼写规则我有在上一篇博客中写到,请大家自行查阅。同样,我们给出罗马字符对应的阿拉伯数字表格。
字母 | M | D | C | L | X | V | I |
---|---|---|---|---|---|---|---|
代表数字 | 1000 | 500 | 100 | 50 | 10 | 5 | 1 |
设计思路:针对这个题,解法同样也有很多,这里我介绍的是我认为比较简单明了的解法。
每两个level之间要用一个减法操作,为什么这么说呢,举个栗子:4,根据规则我们不能用IIII表示而是表示为IV,这个减法同样在9,40,90,400,900的时候使用,so这几种情况也不是很繁琐,我们列个数组把它们表示出来就好惹~
同样遍历顺序从前往后,本着贪心的算法思想,每次从前往后选出最大的字符表示,然后把对应的罗马字符串联起来,也就能完成这道题了。代码如下:
实现代码:
package leetcode;
/**
*
* @ClassName IntegerToRoman.java
* @author Leno E-mail:cliugeek@us-forever.com
* @date 2018年3月7日上午11:36:46
* @Description Given an integer, convert it to a roman numeral.
*
* Input is guaranteed to be within the range from 1 to 3999.
*/
public class IntegerToRoman {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(intToRoman(99));
}
public static String intToRoman(int num) {
String result = "";
String keys[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
int values[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
for(int i = 0;num!=0;i++){
while(num>=values[i]){
num-=values[i];
result+=keys[i];
}
}
return result;
}
}