[leetcode] Integer to Roman | 整数转换成罗马数字
Posted August 14, 2013
on:这题是和amazon wiki上的做法一致,即每次取最右面的single digit,根据当前位数(个位十位之类的)和这个数字本身来算出它的罗马数字(用pattern matching);然后prepend到string builder前面。这题好多做法,但是pattern matching的做法不用考虑4呀9呀之类的,比较清晰。
public String intToRoman(int num) { Map<Integer, Tri> weiToTri = new HashMap<Integer, Tri>(); weiToTri.put(1, new Tri('I', 'V', 'X')); weiToTri.put(2, new Tri('X', 'L', 'C')); weiToTri.put(3, new Tri('C', 'D', 'M')); weiToTri.put(4, new Tri('M', 'F', 'F')); StringBuilder result = new StringBuilder(); int wei = 1; while (num != 0) { int digit = num % 10; result.insert(0, getRomanForDigit(digit, wei, weiToTri)); num /= 10; wei++; } return result.toString(); } private String getRomanForDigit(int digit, int wei, Map<Integer, Tri> weiToTri) { Tri tri = weiToTri.get(wei); String[] patterns = {"", "a", "aa", "aaa", "ab", "b", "ba", "baa", "baaa", "ac"}; String pattern = patterns[digit].replace('a', tri.one).replace('b', tri.five).replace('c', tri.ten); return pattern; }
Tags: math
1 | [leetcode] Integer to Roman | 整数转换成罗马数字 | Miss A's LeetCode Notes
March 11, 2015 at 3:12 pm
[…] // 另外还有一个方法,两种不同的写法是:(前者帮助理解思路,后者写法简洁) // http://blog.csdn.net/linhuanmars/article/details/21145639 // https://leetcodenotes.wordpress.com/2013/08/14/integer-to-roman/ […]