LeetCode -- Integer to Roman
Question:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Analysis:
给出一个整数,将它转换成罗马数字。
注意:保证输入的数字在1~3999之间。
思路: 主要是首先要知道罗马数字与阿拉伯数字之间的转换关系。具体规则自行百度。观察规律可知,只有4,9,40,90……是由右面大的减去左边小的,其他的都是在右边直接累加。因此将所有特殊情况罗列出来即可。
1. 递归的解决方案。
public class Solution { public String intToRoman(int num) { if(num >= 1000) return "M" + intToRoman(num - 1000); if(num >= 900) return "CM" + intToRoman(num - 900); if(num >= 500) return "D" + intToRoman(num - 500); if(num >= 400) return "CD" + intToRoman(num - 400); if(num >= 100) return "C" + intToRoman(num - 100); if(num >= 90) return "XC" + intToRoman(num - 90); if(num >= 50) return "L" + intToRoman(num - 50); if(num >= 40) return "XL" + intToRoman(num -40); if(num >= 10) return "X" + intToRoman(num - 10); if(num >= 9) return "IX" + intToRoman(num - 9); if(num >= 5) return "V" + intToRoman(num - 5); if(num >= 4) return "IV" + intToRoman(num - 4); if(num >= 1) return "I" + intToRoman(num -1); return ""; } }
2. 非递归的解决方案。
public class Solution { public String intToRoman(int num) { String[] str = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"}; int[] val = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000}; String result = ""; for(int i=val.length-1; num != 0; i--) { while(num >= val[i]) { num -= val[i]; result += str[i]; } } return result; } }