Lexi's Leetcode solutions

[leetcode] Integer to Roman | 整数转换成罗马数字

Posted on: August 14, 2013

这题是和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;
  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;

1 Response to "[leetcode] Integer to Roman | 整数转换成罗马数字"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: