問題描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解題思路
將1000,900,500,400,100,90,50,40,10,9,5,4,1與對應的羅馬數字用map存儲,然後根據輸入的數字輸出相應的羅馬數字即可
代碼如下:
class Solution {
map<int, string> iToR;
public:
string findT(int num) {
string s = "";
string tempstr;
for (int i = 0; i < num; i++) {
tempstr = iToR.find(1000)->second;
s = s + tempstr;
}
return s;
}
string findH(int num) {
string s = "";
string tempstr;
if (num == 0) {
return s;
}
if (num < 4) {
for (int i = 0; i < num; i++) {
tempstr = iToR.find(100)->second;
s = s + tempstr;
}
return s;
}
if (num == 4) {
tempstr = iToR.find(400)->second;
s = s + tempstr;
return s;
}
if (num < 9) {
int temp = num - 5;
tempstr = iToR.find(500)->second;
s = s + tempstr;
for (int i = 0; i < temp; i++) {
tempstr = iToR.find(100)->second;
s = s + tempstr;
}
return s;
}
if (num == 9) {
tempstr = iToR.find(900)->second;
s = s + tempstr;
return s;
}
}
string findTen(int num) {
string s = "";
string tempstr;
if (num == 0) {
return s;
}
if (num < 4) {
for (int i = 0; i < num; i++) {
tempstr = iToR.find(10)->second;
s = s + tempstr;
}
return s;
}
if (num == 4) {
tempstr = iToR.find(40)->second;
s = s + tempstr;
return s;
}
if (num < 9) {
int temp = num - 5;
tempstr = iToR.find(50)->second;
s = s + tempstr;
for (int i = 0; i < temp; i++) {
tempstr = iToR.find(10)->second;
s = s + tempstr;
}
return s;
}
if (num == 9) {
tempstr = iToR.find(90)->second;
s = s + tempstr;
return s;
}
}
string findOne(int num) {
string s = "";
string tempstr;
if (num == 0) {
return s;
}
if (num < 4) {
for (int i = 0; i < num; i++) {
tempstr = iToR.find(1)->second;
s = s + tempstr;
}
return s;
}
if (num == 4) {
tempstr = iToR.find(4)->second;
s = s + tempstr;
return s;
}
if (num < 9) {
int temp = num - 5;
tempstr = iToR.find(5)->second;
s = s + tempstr;
for (int i = 0; i < temp; i++) {
tempstr = iToR.find(1)->second;
s = s + tempstr;
}
return s;
}
if (num == 9) {
tempstr = iToR.find(9)->second;
s = s + tempstr;
return s;
}
}
string intToRoman(int num) {
//map<int, string> iToR;
iToR.insert(pair<int, string>(1, "I"));
iToR.insert(pair<int, string>(4, "IV"));
iToR.insert(pair<int, string>(5, "V"));
iToR.insert(pair<int, string>(9, "IX"));
iToR.insert(pair<int, string>(10, "X"));
iToR.insert(pair<int, string>(40, "XL"));
iToR.insert(pair<int, string>(50, "L"));
iToR.insert(pair<int, string>(90, "XC"));
iToR.insert(pair<int, string>(100, "C"));
iToR.insert(pair<int, string>(400, "CD"));
iToR.insert(pair<int, string>(500, "D"));
iToR.insert(pair<int, string>(900, "CM"));
iToR.insert(pair<int, string>(1000, "M"));
int thous = num / 1000;
int huns = (num / 100) % 10;
int tens = (num / 10) % 10;
int ones = num % 10;
string s;
s = findT(thous) + findH(huns) + findTen(tens) + findOne(ones);
return s;
}
};