码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Integer to Roman 解题报告

时间:2014-11-23 17:26:35      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

Integer to Roman

Given an integer, convert it to a roman numeral.

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

bubuko.com,布布扣

SOLUTION 1:

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

罗马数字对照表:

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

bubuko.com,布布扣
 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 }
View Code

 

请至主页君GITHUB:

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

 

LeetCode: Integer to Roman 解题报告

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4116797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!