前言
這周末加上這星期的5天都需要幫導師做一個北郵爛尾的項目,很辛苦,不過知遇之恩確實太大,無以為報,只能竭心盡力
無奈項目是用svn版本庫控制,github的提交記錄又多了一天空白,看著很不爽,哪天我不在github上提交代碼,必然在svn上提交,嘿嘿
題目
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路
題目不難,就是3999以內的阿拉伯數字轉為羅馬數字,之前有一篇文章寫過羅馬數字的特點,見鏈接:http://blog.csdn.net/wzy_1988/article/details/17057929
以3849為例,其實我們只需要考慮每一位的數字即可,對於每一位的數字digit,分為以下幾種情況:
digit == 00 < digit <= 3digit == 45 <= digit <= 9digit == 9
對於每一位,分別處理這5種情況即可
AC代碼
public class Solution {
public String intToRoman(int num) {
StringBuilder result = new StringBuilder();
char[] roman = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
int digit, base = 1000;
for (int i = roman.length + 1; i >= 0 && num > 0; i -= 2, base /= 10) {
digit = num / base;
if (digit == 0) {
continue;
} else if (digit <= 3) {
for (int j = 0; j < digit; j ++) {
result.append(roman[i - 2]);
}
} else if (digit == 4) {
result.append(roman[i - 2]);
result.append(roman[i - 1]);
} else if (digit <= 8) {
result.append(roman[i- 1]);
for (int j = digit - 5; j > 0; j --) {
result.append(roman[i - 2]);
}
} else if (digit == 9) {
result.append(roman[i - 2]);
result.append(roman[i]);
}
num = num % base;
}
return result.toString();
}
}