首页 > 代码库 > [LeetCode]12 Integer to Roman
[LeetCode]12 Integer to Roman
https://oj.leetcode.com/problems/integer-to-roman/
http://fisherlei.blogspot.com/2012/12/leetcode-integer-to-roman.html
public class Solution { // // 把4,9 定义为特殊的字符 // 从大到小适配 public String intToRoman(int num) { if (num < 1 || num > 3999) return null; // Invalid input. StringBuilder sb = new StringBuilder(); while (num > 0) { for (int i : list) { if (num >= i) { sb.append(map.get(i)); num -= i; break; } } } return sb.toString(); } private static final String ONE = "I"; private static final String FIVE = "V"; private static final String TEN = "X"; private static final String FIFTY = "L"; private static final String HUNDRED = "C"; private static final String FIVE_HUNDREDS = "D"; private static final String THOUSAND = "M"; private static final Map<Integer, String> map = new HashMap<>(); private static final List<Integer> list = new ArrayList<>(); static { // Make it unmodifiable map.put(1000, "M"); map.put(900, "CM"); map.put(500, "D"); map.put(400, "CD"); map.put(100, "C"); map.put(90, "XC"); map.put(50, "L"); map.put(40, "XL"); map.put(10, "X"); map.put(9, "IX"); map.put(5, "V"); map.put(4, "IV"); map.put(1, "I"); list.add(1000); list.add(900); list.add(500); list.add(400); list.add(100); list.add(90); list.add(50); list.add(40); list.add(10); list.add(9); list.add(5); list.add(4); list.add(1); } }
[LeetCode]12 Integer to Roman
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。