LeetCode: Integer to Roman 解题报告

时间:2023-03-09 15:58:02
LeetCode: Integer to Roman  解题报告

Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

LeetCode: Integer to Roman  解题报告

SOLUTION 1:

从大到小的贪心写法。从大到小匹配,尽量多地匹配当前的字符。

罗马数字对照表:

http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

 package Algorithms.string;

 public class IntToRoman {
public String intToRoman(int num) {
int nums[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuilder sb = new StringBuilder(); int i = 0;
// 使用贪心法。尽量拆分数字
while (i < nums.length) {
if (num >= nums[i]) {
sb.append(romans[i]);
num -= nums[i];
} else {
i++;
}
} return sb.toString();
}
}

2015.1.12 redo:

 public String intToRoman(int num) {
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; /*
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X" IX V, IV, I
*/
String[] strs = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; int i = 0;
StringBuilder sb = new StringBuilder();
// greedy.
while (i < nums.length) {
// bug 1: should use ">="
if (num >= nums[i]) {
sb.append(strs[i]);
// bug 2: should remember to reduce the nums[i].
num -= nums[i];
} else {
i++;
}
} return sb.toString();
}

请至主页君GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/IntToRoman.java