1. 程式人生 > >Leetcode刷題記——12. Integer to Roman(阿拉伯數字轉羅馬數字)

Leetcode刷題記——12. Integer to Roman(阿拉伯數字轉羅馬數字)

一、題目敘述:

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));
    }
}