题目:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
链接:https://leetcode.com/problems/integer-to-roman/#/description
4/9/2017
18%, 115ms
1 public class Solution { 2 public String intToRoman(int num) { 3 HashMap<Integer, Character> hm = new HashMap<Integer, Character>(); 4 StringBuilder sb = new StringBuilder(); 5 hm.put(1, 'I'); 6 hm.put(5, 'V'); 7 hm.put(10, 'X'); 8 hm.put(50, 'L'); 9 hm.put(100, 'C'); 10 hm.put(500, 'D'); 11 hm.put(1000, 'M'); 12 13 while (num > 0) { 14 if (num / 1000 != 0) { 15 int count = num / 1000; 16 num -= 1000 * count; 17 while (count > 0) { 18 sb.append(hm.get(1000)); 19 count--; 20 } 21 } else if (num / 900 != 0) { 22 sb.append(hm.get(100)); 23 sb.append(hm.get(1000)); 24 num -= 900; 25 } else if (num / 500 != 0) { 26 sb.append(hm.get(500)); 27 num -= 500; 28 } else if (num / 400 != 0) { 29 sb.append(hm.get(100)); 30 sb.append(hm.get(500)); 31 num -= 400; 32 } else if (num / 100 != 0) { 33 int count = num / 100; 34 num -= 100 * count; 35 while (count > 0) { 36 sb.append(hm.get(100)); 37 count--; 38 } 39 } else if (num / 90 != 0) { 40 sb.append(hm.get(10)); 41 sb.append(hm.get(100)); 42 num -= 90; 43 } else if (num / 50 != 0) { 44 sb.append(hm.get(50)); 45 num -= 50; 46 } else if (num / 40 != 0) { 47 sb.append(hm.get(10)); 48 sb.append(hm.get(50)); 49 num -= 40; 50 } else if (num / 10 != 0) { 51 int count = num / 10; 52 num -= 10 * count; 53 while (count > 0) { 54 sb.append(hm.get(10)); 55 count--; 56 } 57 } else if (num / 9 != 0) { 58 sb.append(hm.get(1)); 59 sb.append(hm.get(10)); 60 num -= 9; 61 } else if (num / 5 != 0) { 62 sb.append(hm.get(5)); 63 num -= 5; 64 } else if (num / 4 != 0) { 65 sb.append(hm.get(1)); 66 sb.append(hm.get(5)); 67 num -= 4; 68 } else { 69 while (num > 0) { 70 sb.append(hm.get(1)); 71 num--; 72 } 73 } 74 } 75 return sb.toString(); 76 } 77 }
其实可以多列出来很多case,比如9,4的情况。甚至可以列出来所有的例子
别人的答案:
1 public class Solution { 2 public String intToRoman(int num) { //Roman: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 3 StringBuilder result = new StringBuilder(); 4 String [] symbol = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 5 int [] value = {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 6 for(int i = 0; num != 0; i++){ 7 while(num >= value[i]){ 8 num -= value[i]; 9 result.append(symbol[i]); 10 } 11 } 12 return result.toString(); 13 } 14 }
https://discuss.leetcode.com/topic/12384/simple-solution
1 public static String intToRoman(int num) { 2 String M[] = {"", "M", "MM", "MMM"}; 3 String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 4 String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 5 String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 6 return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; 7 }
更多讨论:https://discuss.leetcode.com/category/20/integer-to-roman