首先要解决这道题,你应该首先了解罗马数字。参见维基百科https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97。罗马数字主要由7个字母来构成,不同的字母代表不同的十进制数值。
I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
这道题,我的解法还是稍显复杂,解法复杂的一个弊端就是调试和维护会比较困难。我的解法的核心思想是对整数,比如说2987,从右到左依次抽取个位数字,十位数字和百位数字,然后根据数字的大小,来选择应该加上什么罗马数字。比如个位数字是4,则应该加上IV,如果是9,则应该加上IX。我的代码如下:
string intToRoman(int num) {
int lastDigit = 0, pos = 0, i;
string result = "", one = "", five = "", ten = "", tmp;
do {
lastDigit = num%10; // 抽取数字
num /= 10;
tmp = "";
if (lastDigit != 0) {
if (pos == 0) { // pos为0代表个位数字,为1代表十位数字
one = "I";
five = "V";
ten = "X";
} else if (pos == 1) {
one = "X";
five = "L";
ten = "C";
} else if (pos == 2) {
one = "C";
five = "D";
ten = "M";
} else if (pos == 3) {
one = "M";
}
if (pos != 3) {
if (lastDigit <= 3 || (lastDigit != 4 && lastDigit !=9)) {
if (lastDigit <= 3) {
for (i=0; i<lastDigit; i++) {
tmp += one;
}
} else {
tmp = five;
for (i=0; i<lastDigit-5; i++) {
tmp += one;
}
}
} else if (lastDigit == 9) {
tmp = one+ten;
} else {
tmp = one+five;
}
} else {
for (i=0; i<lastDigit; i++) {
tmp += one;
}
}
result = tmp + result;
}
pos++;
} while (num);
return result;
}
更简单也更易于理解的一种做法应该是打表,而其核心思想是贪心。
string intToRoman(int num) {
string str;
string symbols[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int values[] = {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
for(int i=0;num!=0;++i) // 用num是否为0来判断是否终止
{
while(num>=value[i])
{
num-=value[i];
str+=symbol[i];
}
}
return str;
}