12. Integer to Roman
2017-09-20 本文已影响0人
Al73r
题目
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析
首先查了下罗马数字的书写规则
https://www.douban.com/note/335254352/
发现可以从大到小依次书写,比较简单,不多说直接上代码。
实现
class Solution {
public:
string intToRoman(int num) {
string ans;
while(num>=900){
if(num>=1000){
num -= 1000;
ans += "M";
}
else{
num -= 900;
ans += "CM";
}
}
while(num>=400){
if(num>=500){
num -= 500;
ans += "D";
}
else{
num -= 400;
ans += "CD";
}
}
while(num>=90){
if(num>=100){
num -= 100;
ans += "C";
}
else{
num -= 90;
ans += "XC";
}
}
while(num>=40){
if(num>=50){
num -= 50;
ans += "L";
}
else{
num -= 40;
ans += "XL";
}
}
while(num>=9){
if(num>=10){
num -= 10;
ans += "X";
}
else{
num -= 9;
ans += "IX";
}
}
while(num>=4){
if(num>=5){
num -= 5;
ans += "V";
}
else{
num -= 4;
ans += "IV";
}
}
while(num>0){
num--;
ans += "I";
}
return ans;
}
};
思考
这里我比较懒,就直接用了若干循环完成了。
其实,还可以将这些循环两两分为一组,放入一个大循环内。
或者直接将两个字母的组合例如“IX”等变为新的一个单元,这样更简单。
另外更讨巧的方法可以是把个十百千位的各种情况都列出来,这样可以直接输出,代码如下。
class Solution {
public:
string intToRoman(int num) {
char* digit[10] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
char* ten[10] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
char* hundreds[10] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
char* thousand[4] = {"","M","MM","MMM"};
string answer = "";
answer = answer + thousand[num/1000] + hundreds[(num/100)%10] + ten[(num/10)%10] + digit[(num)%10];
return answer;
}
};