问题大意是将整数(1~3999)转换为罗马数字形式,并以字符串的形式返回。至于罗马数字可以参考https://en.wikipedia.org/wiki/Roman_numerals中的说法。
很暴力的解决方案,直接看代码吧,时间复杂度和空间复杂度均为常数,即O(1)。
代码的运行时间是82ms
1 package cn.dalt.leetcode; 2 3 /** 4 * Created by dalt on 2017/6/18. 5 */ 6 public class IntegertoRoman { 7 public String intToRoman(int num) { 8 StringBuilder s = new StringBuilder(); 9 char[] signatures = new char[]{'I', 'V', 'X', 'L', 'C', 'D', 'M', ' ', ' '}; 10 int[] valueRepresented = new int[]{1, 5, 10, 50, 100, 500, 1000, 5000, 10000}; 11 for (int i = signatures.length - 1; i >= 0; i -= 2) { 12 int tenPos = i; 13 int fivePos = i - 1; 14 int onePos = i - 2; 15 int oneValue = valueRepresented[onePos]; 16 int value = (num / oneValue) % 10; 17 if (value <= 3) { 18 for (int j = 0; j < value; j++) { 19 s.append(signatures[onePos]); 20 } 21 } else if (value <= 8) { 22 for (int j = 4; j >= value; j--) { 23 s.append(signatures[onePos]); 24 } 25 s.append(signatures[fivePos]); 26 for (int j = 5; j < value; j++) { 27 s.append(signatures[onePos]); 28 } 29 } else { 30 if (value == 9) { 31 s.append(signatures[onePos]); 32 } 33 s.append(signatures[tenPos]); 34 } 35 } 36 return s.toString(); 37 } 38 }
顺便贴上其姊妹问题Roman to Integer的代码:
1 package cn.dalt.leetcode; 2 3 4 /** 5 * Created by dalt on 2017/6/18. 6 */ 7 public class RomantoInteger { 8 9 static int[] ranks = new int[256]; 10 11 static { 12 char[] signatures = new char[]{'I', 'V', 'X', 'L', 'C', 'D', 'M'}; 13 int[] valueRepresented = new int[]{1, 5, 10, 50, 100, 500, 1000}; 14 for (int i = 0, bound = signatures.length; i < bound; i++) { 15 ranks[signatures[i]] = valueRepresented[i]; 16 } 17 } 18 19 public int romanToInt(String s) { 20 int curMax = 0; 21 int lastDifferentValue = 0; 22 int curSign = 1; 23 int result = 0; 24 for (int i = s.length() - 1; i >= 0; i--) { 25 char c = s.charAt(i); 26 int v = ranks[c]; 27 if (v >= curMax) { 28 curMax = v; 29 lastDifferentValue = v; 30 curSign = 1; 31 } else if (v < lastDifferentValue) { 32 lastDifferentValue = v; 33 curSign *= -1; 34 } 35 result += curSign * v; 36 } 37 return result; 38 } 39 }