leetcode-12-integer to roman

题目

数字转罗马字符

分析

数字在1-3999之间
罗马字符:I-1,V-5,X-10,L-50,C-100,D-500,M-1000
个位用I和V表示
十位用X和L表示
百位用C和D表示
千位用M表示

C++代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
string (int num) {
char a [] ={'I','V','X','L','C','D','M'};
string s = "";
int x =0;
while(num!=0){
int y = num%10;
num/=10;
if(y<4){
for(int i=0;i<y;i++){
s+=a[x*2];
}
}
else if(y==4){
s+=a[x*2+1];
s+=a[x*2];
}
else if(y==5){
s+=a[x*2+1];
}
else if(y<9){
for(int i=0;i<y-5;i++){
s+=a[x*2];
}
s+=a[x*2+1];
}
else if(y==9){
s+=a[(x+1)*2];
s+=a[(x)*2];
}
x++;
}
reverse(s.begin(),s.end());
return s;
}
};