罗马数字的规则如下:
·个位数举例
I, 1 II, 2 III, 3 IV, 4 V, 5 VI, 6 VII, 7 VIII, 8 IX, 9
·十位数举例
X, 10 XI, 11 XII, 12 XIII, 13 XIV, 14 XV, 15 XVI, 16 XVII, 17 XVIII, 18 XIX, 19 XX, 20 XXI, 21 XXII, 22 XXIX, 29 XXX, 30 XXXIV, 34 XXXV, 35 XXXIX, 39 XL, 40 L, 50 LI, 51 LV, 55 LX, 60 LXV, 65 LXXX, 80 XC, 90 XCIII, 93 XCV, 95 XCVIII, 98 XCIX, 99
·百位数举例
C, 100 CC, 200 CCC, 300 CD, 400 D, 500 DC, 600 DCC, 700 DCCC, 800 CM, 900 CMXCIX, 999
·千位数举例
M, 1000 MC, 1100 MCD, 1400 MD, 1500 MDC, 1600 MDCLXVI, 1666 MDCCCLXXXVIII, 1888 MDCCCXCIX, 1899 MCM, 1900 MCMLXXVI, 1976 MCMLXXXIV, 1984 MCMXC, 1990 MM, 2000 MMMCMXCIX, 3999
罗马数字是古罗马使用的数字系统.现今仍很常见.
简单的罗马数字见下:
*I - 1
* II - 2
* III - 3
* IV - 4
* V - 5
* VI - 6
* X - 10
* L - 50
* C - 100
* D - 500
* M - 1000
罗马数字共有七个, 即I(1), V(5), X(10), L(50), C(100), D(500), M(1000).按照下面的规则可以表示任意正整数.
* 重复数次:一个罗马数字重复几次, 就表示这个数的几倍.
* 右加左减:在一个较大的罗马数字的右边记上一个较小的罗马数字, 表示大数字加小数字.在一个较大的数字的左边记上一个较小的罗马数字, 表示大数字减小数字.但是, 左减不能跨越等级.比如, 99不可以用IC表示, 用XCIX表示.
* 加线乘千:在一个罗马数字的上方加上一条横线或者在右下方写M, 表示将这个数字乘以1000, 即是原数的1000倍.同理, 如果上方有两条横线, 即是原数的1000000倍.
* 单位限制:同样单位只能出现3次, 如40不能表示为XXXX, 而要表示为XL.
代码如下:
string intToRoman(int num) {
string str,str2,str1,str0;
int qian = num / 1000;
string str3(qian, 'M');
str += str3;
int bai = (num % 1000) / 100;
if (bai > 3)
{
if (bai == 4)str2 = "CD";
else if (bai == 5)str2 = "D";
else if (bai < 9)
{
str2.assign(bai - 5, 'C');
str2 = 'D' + str2;
}
else str2 = "CM";
}
else if (bai == 0)str2 = "";
else str2.assign(bai, 'C');
int shi=(num%100)/10;
if (shi > 3)
{
if (shi == 4)str1 = "XL";
else if (shi == 5)str1 = "L";
else if (shi < 9)
{
str1.assign(shi - 5, 'X');
str1 = 'L' + str1;
}
else str1 = "XC";
}
else if (shi == 0)str1 = "";
else str1.assign(shi, 'X');
int ge = num % 10;
if (ge > 3)
{
if (ge == 4)str0 = "IV";
else if (ge == 5)str0 = "V";
else if (ge < 9)
{
str0.assign(ge - 5, 'I');
str0 = 'V' + str0;
}
else str0 = "IX";
}
else if (ge == 0)str0 = "";
else str0.assign(ge, 'I');
str = str3 + str2 + str1+str0;
return str;
}
在网上发现了更简短的代码:
class Solution {
public:
string intToRoman(int num) {
string thousand[4] = {"", "M", "MM","MMM"};
string hundred[11] = {"", "C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
string ten[11] = {"", "X", "XX","XXX","XL","L","LX","LXX","LXXX","XC"};
string one[11] = {"", "I","II","III","IV","V","VI","VII","VIII","IX"};
string result = "";
string* trans[4] = {one, ten, hundred, thousand};
int index = 0;
while (num > 0) {
result = trans[index][num % 10] + result;
num = num / 10;
index++;
}
return result;
}
};