Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
SOLUTION 1:
从大到小的贪心写法。从大到小匹配,尽量多地匹配当前的字符。
罗马数字对照表:
http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
1 package Algorithms.string; 2 3 public class IntToRoman { 4 public String intToRoman(int num) { 5 int nums[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 6 String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 7 8 StringBuilder sb = new StringBuilder(); 9 10 int i = 0; 11 // 使用贪心法。尽量拆分数字 12 while (i < nums.length) { 13 if (num >= nums[i]) { 14 sb.append(romans[i]); 15 num -= nums[i]; 16 } else { 17 i++; 18 } 19 } 20 21 return sb.toString(); 22 } 23 }
请至主页君GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/IntToRoman.java
时间: 2024-10-11 00:05:46