題目: LeetCode - 12. Integer to Roman

題目說明

給一個整數,將此整數轉為羅馬數字。

解題思路

建表比對即可,特別的是 4、9、40、90、400、900 也需要建。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string intToRoman(int num) {
string res;
int pos = 12;
pair<string, int> dict[] = {{"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}};
while(num > 0)
{
while(pos && dict[pos].second > num)
--pos;
while(num >= dict[pos].second)
res += dict[pos].first, num -= dict[pos].second;
}
return res;
}
};