1. 程式人生 > >LeetCode Integer To Roman

LeetCode Integer To Roman

Problem

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Roman To Integer是對應問題。即將整數轉換成對應的羅馬數字。羅馬數字規則見wiki:羅馬數字規則

Java 實現(個人解法)


package com.coderli.leetcode.algorithms.medium;

/**
 * Given an integer, convert it to a roman numeral.
 * <p>
 * Input is guaranteed to be within the range from 1 to 3999
 *
 * @author li.hzh
 */
public class IntegerToRoman { public static void main(String[] args) { IntegerToRoman integerToRoman = new IntegerToRoman(); System.out.println(integerToRoman.intToRoman(1)); System.out.println(integerToRoman.intToRoman(10)); System.out.println(integerToRoman.intToRoman
(90)); System.out.println(integerToRoman.intToRoman(1437)); } public String intToRoman(int num) { int times = 1; String result = ""; while (num > 0) { int tempIntValue = num % 10; num /= 10; String tempStrValue = ""; if
(tempIntValue == 5) { switch (times) { case 1: result = tempStrValue = "V"; break; case 2: result = "L" + result; break; case 3: result = "D" + result; break; } } else if (tempIntValue % 5 <= 3) { int length = tempIntValue; switch (times) { case 1: if (tempIntValue > 5) { tempStrValue = "V"; length = tempIntValue - 5; } for (int i = 0; i < length; i++) { tempStrValue += "I"; } result = tempStrValue + result; break; case 2: if (tempIntValue > 5) { tempStrValue = "L"; length = tempIntValue - 5; } for (int i = 0; i < length; i++) { tempStrValue += "X"; } result = tempStrValue + result; break; case 3: if (tempIntValue > 5) { tempStrValue = "D"; length = tempIntValue - 5; } for (int i = 0; i < length; i++) { tempStrValue += "C"; } result = tempStrValue + result; break; case 4: for (int i = 0; i < tempIntValue; i++) { tempStrValue += "M"; } result = tempStrValue + result; break; } } else { switch (times) { case 1: result = tempIntValue < 5 ? "IV" + result : "IX" + result; break; case 2: result = tempIntValue < 5 ? "XL" + result : "XC" + result; break; case 3: result = tempIntValue < 5 ? "CD" + result : "CM" + result; break; } } times++; } return result; } }

分析

上面解法其實受到了羅馬轉整數問題的慣性思維。把思維限制到了羅馬數字只能用基礎的I、V、X等元素上。羅馬數字的規則不再介紹了。思路其實跟羅馬轉數字一致,抓住羅馬數字其實也是個位、十位、百位等一位一位組合起來的,因此我們一位一位的生成對應的羅馬數字即可。

正因為羅馬數字也是一位一位對應的,因此網上流傳一個簡便的寫法,程式碼很簡潔:


public static String change(int num) {
		String [][]str = 
			{
		            {"","I","II","III","IV","V","VI","VII","VIII","IX"},
		            {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
		            {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
		            {"","M","MM","MMM"}
			};
		String roman = (str[3][num / 1000 % 10])+(str[2][num / 100 % 10])+(str[1][num / 10 % 10])+(str[0][num % 10]);
		
		return roman;


把個十百千各位可能羅馬字元準備好,然後直接計算整數對應位上的值,取出陣列中對應索引位的羅馬值拼到一起就可以了。