一、题目叙述:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
二、解题思路:
这次是自己想的哈,吼吼吼~~~~其实只要知道罗马数字书写的规律,就可以写出来了,完全是找规律题,并没有什么不容易考虑到的限制条件。说说我的思路:
1.首先观察罗马数字的规律,每个罗马数字不会连续出现4个相同的。
2.从高位到低位,一位一位转换。首先把罗马数字和其对应的阿拉伯数字放入平行数组里,ro[]和roam[];
3.规律主要是这样的,比如百位数是x,当x在1到3之间,可以只用x个代表百的罗马数字‘C’ 表示;当x是4的时候,得用一个表示100的罗马数字‘C’和一个表示500的罗马数字‘D’表示;当x大于4小于9时,用一个表示500的罗马数字和x-5个表示100的罗马数字表示;当x为9时,就用一个表示100的罗马数字'C'和一个表示1000的罗马数字‘M’表示;
额。。。写的不够清楚哈,自行百度看规律~~~
三、源源源码:
public class Solution
{
public String intToRoman(int num)
{
String a = "";
int[] ro = {1000, 500, 100, 50, 10, 5, 1};
char[] roma = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
for (int i = 0; i < 7; i = i + 2)
{
int temp = num / ro[i];
if (temp < 4)
for (int j = 0; j < temp; j++)
a = a + roma[i] + "";
else if (temp == 4)
a = a + roma[i] + roma[i-1] + "";
else if (temp > 4 && temp < 9)
{
a = a + roma[i-1] + "";
for (int j = 0; j < temp - 5; j++)
a = a + roma[i] + "";
}
else if (temp == 9)
a = a + roma[i] + roma[i-2] + "";
num = num - temp * ro[i];
}
return a;
}
public static void main(String[] args)
{
int i = 90;
Solution a = new Solution();
System.out.println(a.intToRoman(i));
}
}