-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path整数转罗马数字.cpp
132 lines (122 loc) · 2.71 KB
/
整数转罗马数字.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <iostream>
#include <string>
using namespace std;
// 此题的关键是建议一个查询表!!
// 用一定空间来换取效率
class Solution {
public:
string intToRoman(int num)
{
string res = "";
if (num >= 1 && num <= 3999)
{
int i = 0;
while (num != 0)
{
int temp = num % 10;
num /= 10;
res = string(Roman[i][temp]) + res;
++i;
}
}
return res;
}
//2019.3.1
string intToRoman(int num) {
string roman;
while (num) {
if (num >= 1000)
{ num -= 1000; roman += 'M'; }
else
{
if (num >= 900)
{ num -= 900; roman += 'C'; roman += 'M'; }
else
{
if (num >= 500)
{ num -= 500; roman += 'D'; }
else
{
if (num >= 400)
{ num -= 400; roman += 'C'; roman += 'D'; }
else
{
if (num >= 100)
{ num -= 100; roman += 'C'; }
else
{
if (num >= 90)
{ num -= 90; roman += 'X'; roman += 'C'; }
else
{
if (num >= 50)
{ num -= 50; roman += 'L'; }
else
{
if (num >= 40)
{ num -= 40; roman += 'X'; roman += 'L'; }
else
{
if (num >= 10)
{ num -= 10; roman += 'X'; }
else
{
if (num >= 9)
{ num -= 9; roman += 'I'; roman += 'X'; }
else
{
if (num >= 5)
{ num -= 5; roman += 'V'; }
else
{
if (num >= 4)
{ num -= 4; roman += 'I'; roman += 'V'; }
else
{ num -= 1; roman += 'I'; }
}
}
}
}
}
}
}
}
}
}
}
}
return roman;
}
//update 2019.9.25
string intToRoman(int num) {
map<int, string> mapRom = { { 1,"I" },{ 4,"IV" },{ 5,"V" },{ 9,"IX" },{ 10,"X" },{ 40,"XL" },{ 50,"L" },{ 90,"XC" },{ 100,"C" },{ 400,"CD" },{ 500,"D" },{ 900,"CM" },{ 1000,"M" } };
map<int, string>::reverse_iterator r_iter;
string ret;
r_iter = mapRom.rbegin();
while (r_iter != mapRom.rend())
{
if (num >= r_iter->first)
{
ret += r_iter->second;
num -= r_iter->first;
}
else
r_iter++;
}
return ret;
}
private:
//4是说明有4个,第一个10说明每个里面有10个字符串,第二个10说明每个字符串有10个字符
const char Roman[4][10][10]={
{"","I","II" ,"III" ,"IV" ,"V" ,"VI" ,"VII" ,"VIII" ,"IX" },//1-9
{"","X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" },//10-90
{ "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },//100-900
{ "", "M", "MM", "MMM" }//1000-3000
};
};
int main()
{
Solution a;
cout << a.intToRoman(3999) << endl;
system("pause");
}