mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
36 lines
1018 B
Markdown
36 lines
1018 B
Markdown
![]() |
# [12. Integer to Roman](https://leetcode.com/problems/integer-to-roman/)
|
||
|
# 思路
|
||
|
阿拉伯数字转罗马数字。
|
||
|
按照题意将所有可能的罗马数字列出来,再从大到小看能不能将阿拉伯数字转换成罗马数字。详细过程见代码。
|
||
|
|
||
|
# C++
|
||
|
``` C++
|
||
|
class Solution {
|
||
|
public:
|
||
|
string intToRoman(int num) {
|
||
|
map<int, string>int2rom;
|
||
|
string res = "";
|
||
|
int nums[13] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
|
||
|
int2rom[1] = "I";
|
||
|
int2rom[5] = "V";
|
||
|
int2rom[10] = "X";
|
||
|
int2rom[50] = "L";
|
||
|
int2rom[100] = "C";
|
||
|
int2rom[500] = "D";
|
||
|
int2rom[1000] = "M";
|
||
|
int2rom[4] = "IV";
|
||
|
int2rom[9] = "IX";
|
||
|
int2rom[40] = "XL";
|
||
|
int2rom[90] = "XC";
|
||
|
int2rom[400] = "CD";
|
||
|
int2rom[900] = "CM";
|
||
|
for(int i = 12; i >= 0; i--){
|
||
|
int tmp = num / nums[i];
|
||
|
while(tmp--) res += int2rom[nums[i]];
|
||
|
num %= nums[i];
|
||
|
}
|
||
|
return res;
|
||
|
}
|
||
|
};
|
||
|
```
|