首页 > 代码库 > LeetCode: Integer to Roman 解题报告
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.
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
LeetCode: Integer to Roman 解题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。