前言
这周末加上这星期的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.
Input is guaranteed to be within the range from 1 to 3999.
思路
题目不难,就是3999以内的阿拉伯数字转为罗马数字,之前有一篇文章写过罗马数字的特点,见链接:
http://blog.youkuaiyun.com/wzy_1988/article/details/17057929
以3849为例,其实我们只需要考虑每一位的数字即可,对于每一位的数字digit,分为以下几种情况:
- digit == 0
- 0 < digit <= 3
- digit == 4
- 5 <= digit <= 9
- digit == 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();
}
}