题目
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
把数字变成罗马字符串
1 之前那道题,考虑4,9的特殊情况也能够在逻辑中处理。所以这题目一直卡在这里。当中也写出来,不过ifelse太多,不合适。
2 之后考虑,直接在字典里把所有4,9的情况都写进去,这样一来,逻辑上面的代码容易多了,一劳永逸。
3 逻辑上面,从大到小,对于数,有字符串对应,一直用贪心法完成。
4 用StringBuffer ,不要用String
public class Solution {
public String intToRoman(int num) {
if(num < 1 || num > 3999){
return "-1";
}
int[] aArray = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] rArray = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuffer rNumber = new StringBuffer();
for(int i=0; i<aArray.length; i++){
while(num >= aArray[i]){
rNumber .append( rArray[i]);
num -= aArray[i];
}
}
return new String(rNumber);
}
}