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

【leetcode】12. Integer to Roman

时间:2016-06-14 06:21:41      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

Given an integer, convert it to a roman numeral.

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

解题思路:

注意到用例比较少,所以采用以空间换时间的方法,把所有的结果列出,然后组合出输入值n的字符串即可。

具体代码:

 1 public class Solution {
 2     public static String intToRoman(int num) {
 3         String[][] array={
 4                 {"","I","II","III","IV","V","VI","VII","VIII","IX"},//0-9
 5                 {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},//10-90
 6                 {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},//100-900
 7                 {"","M","MM","MMM"}//1000-3000
 8         };
 9         StringBuilder sb = new StringBuilder();
10         int n=num/1000;
11         sb.append(array[3][n]);
12         num=num%1000;
13         
14         n=num/100;
15         sb.append(array[2][n]);
16         num=num%100;
17         
18         n=num/10;
19         sb.append(array[1][n]);
20         num=num%10;
21         
22         sb.append(array[0][num]);
23        
24         return sb.toString();
25     }
26 }

 

【leetcode】12. Integer to Roman

标签:

原文地址:http://www.cnblogs.com/godlei/p/5582609.html

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