【leetcode】12. Integer to Roman

题目描述:

Given an integer, convert it to a roman numeral.

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

解题思路:

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

具体代码:

 public class Solution {
public static String intToRoman(int num) {
String[][] array={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},//0-9
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},//10-90
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},//100-900
{"","M","MM","MMM"}//1000-3000
};
StringBuilder sb = new StringBuilder();
int n=num/1000;
sb.append(array[3][n]);
num=num%1000; n=num/100;
sb.append(array[2][n]);
num=num%100; n=num/10;
sb.append(array[1][n]);
num=num%10; sb.append(array[0][num]); return sb.toString();
}
}
上一篇:Python 爬虫入门(一)——爬取糗百


下一篇:Visual Studio 2010安装教程