2014年4月8日 星期二

[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.
Solution:O(n)

public class Solution {
    public static final String[] unit = { "I", "X", "C", "M" };
    public static final String[] fiveunit = { "V", "L", "D" };

    public String intToRoman(int num) {
 String ret = "";
 int digit = 0;
 while (num > 0) {
  ret = getNum(num % 10, digit) + ret;
  num /= 10;
  digit++;
 }
 return ret;
    }

    public String getNum(int num, int digit) {
 String ret = "";
 if (num <= 3)
  ret += pending(num, unit[digit]);
 else if (num >= 5 && num <= 8) {
  ret += fiveunit[digit];
  ret += pending(num - 5, unit[digit]);
 } else if (num == 4) {
  ret += (unit[digit] + fiveunit[digit]);
 } else if (num == 9) {
  ret += (unit[digit] + unit[digit + 1]);
 }
 return ret;
    }

    public String pending(int count, String s) {
 String ret = "";
 for (int i = 0; i < count; i++) {
  ret += s;
 }
 return ret;
    }
}
Key Concept: Each digit has similar behavior, so check getNum(int num, int digit)

沒有留言:

張貼留言