coding
unsky
deepdim
thought

Integer to Roman

ID12:Integer to Roman Add to List QuestionEditorial Solution My Submissions
Total Accepted: 85662
Total Submissions: 202008
Difficulty: Medium
Contributors: Admin
Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

这道题目需要一定的背景知识。
罗马数字的表示方法可以参考wiki:
https://en.wikipedia.org/wiki/Roman_numerals

1
2
3
4
5
6
7
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000

字母可以重复,但不超过三次,当需要超过三次时,用与下一位的组合表示:

1
2
I: 1, II: 2, III: 3, IV: 4
C: 100, CC: 200, CCC: 300, CD: 400

所以需要特殊处理的数字包括:

1
2
3
4
5
6
7
8
9
10
11
12
13
I: 1
IV: 4
V: 5
IX: 9
X: 10
XL: 40
L: 50
XC: 90
C: 100
CD: 400
D: 500
CM: 900
M: 1000

例如:3600这个数

1
2
3
4
3600>1000 3600/1000=3 循环三次M,3600%1000=600;
600>400 600/400=1 循环一次CD,600%400=200;
200>100 200/100=2 循环两次C, 200%100=0;
OVER;

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
string intToRoman(int num) {
string roman[]={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
int val[13]={1,4,5,9,10,40,50,90,100,400,500,900,1000};
string result;
int count;
for(int i=12;i>=0;i--)
{ if(num>=val[i])
{ count=num/val[i];
num=num%val[i];
for(int j=0;j<count;j++)
result.append(roman[i]);
}}
return result;
}
};

坚持原创技术分享,您的支持将鼓励我继续创作!