Given an integer, convert it to a roman numeral. html
Input is guaranteed to be within the range from 1 to 3999. java
https://oj.leetcode.com/problems/integer-to-roman/ app
思路1:構造法,每一位構造而後拼接。每一位表示的字母雖然不一樣,可是規則是同樣的,因此考慮每一位上0-9的表現形式,而後拼接起來。(詳見參考1) ide
思路2:採用貪心策略,每次選擇能表示的最大的值,把對應的字符串鏈接起來,代碼及其簡潔。 ui
貪心: idea
public class Solution { public String intToRoman(int num) { String[] str = new String[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; int[] val = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; StringBuilder sb = new StringBuilder(); for (int i = 0; num > 0; i++) { while (num >= val[i]) { num -= val[i]; sb.append(str[i]); } } return sb.toString(); } public static void main(String[]args){ System.out.println(new Solution().intToRoman(999)); } }
參考: .net
http://www.cnblogs.com/zhaolizhen/p/romannumber.html code
http://blog.csdn.net/havenoidea/article/details/11848921 htm