12. Integer to Roman
阿新 • • 發佈:2018-09-05
clas order map pre build sort array ger reverse
list的反轉
Collections.sort(list, Collections.reverseOrder());
1 class Solution { 2 public String intToRoman(int num) { 3 HashMap<Integer, String> map = new HashMap<>(); 4 map.put(1, "I"); 5 map.put(4, "IV"); 6 map.put(5, "V"); 7 map.put(9, "IX");8 map.put(10, "X"); 9 map.put(40, "XL"); 10 map.put(50, "L"); 11 map.put(90, "XC"); 12 map.put(100, "C"); 13 map.put(400, "CD"); 14 map.put(500, "D"); 15 map.put(900, "CM"); 16 map.put(1000, "M"); 17 18 StringBuilder sb = newStringBuilder(); 19 List<Integer> integers = new ArrayList<Integer>(map.keySet()); 20 Collections.sort(integers, Collections.reverseOrder()); 21 for(int integer : integers) { 22 int quotient = num / integer; 23 for(int i = 0; i < quotient; i++) {24 sb.append(map.get(integer)); 25 } 26 num = num % integer; 27 } 28 29 return sb.toString(); 30 } 31 }
12. Integer to Roman