# 题目描述

``字符          数值I             1V             5X             10L             50C             100D             500``M             1000``

• I 可以放在 V (5) 和 X (10) 的左边，来表示 4 和 9。
• X 可以放在 L (50) 和 C (100) 的左边，来表示 40 和 90。
• C 可以放在 D (500) 和 M (1000) 的左边，来表示 400 和 900。

``输入: 3``输出: "III"``

``输入: 4``输出: "IV"``

``输入: 9``输出: "IX"``

``输入: 58输出: "LVIII"``解释: L = 50, V = 5, III = 3.``

``输入: 1994输出: "MCMXCIV"``解释: M = 1000, CM = 900, XC = 90, IV = 4.``

# 贪心解法

``class Solution {int[] val = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};String[] str = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};public String intToRoman(int x) {StringBuilder sb = new StringBuilder();for (int i = 0; i < val.length && x > 0; i++) {int cv = val[i];String cs = str[i];while (x >= cv) {sb.append(cs);x -= cv;}}return sb.toString();}``}``

1 声望

0 粉丝

0 条评论

# 题目描述

``字符          数值I             1V             5X             10L             50C             100D             500``M             1000``

• I 可以放在 V (5) 和 X (10) 的左边，来表示 4 和 9。
• X 可以放在 L (50) 和 C (100) 的左边，来表示 40 和 90。
• C 可以放在 D (500) 和 M (1000) 的左边，来表示 400 和 900。

``输入: 3``输出: "III"``

``输入: 4``输出: "IV"``

``输入: 9``输出: "IX"``

``输入: 58输出: "LVIII"``解释: L = 50, V = 5, III = 3.``

``输入: 1994输出: "MCMXCIV"``解释: M = 1000, CM = 900, XC = 90, IV = 4.``

# 贪心解法

``class Solution {int[] val = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};String[] str = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};public String intToRoman(int x) {StringBuilder sb = new StringBuilder();for (int i = 0; i < val.length && x > 0; i++) {int cv = val[i];String cs = str[i];while (x >= cv) {sb.append(cs);x -= cv;}}return sb.toString();}``}``