File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ // 模拟
2+ // Time Complexity: O(1)
3+ // 由于 valueSymbols 长度是固定的,且这 13 字符中的每个字符的出现次数均不会超过 3,
4+ // 因此循环次数有一个确定的上限。对于本题给出的数据范围,循环次数不会超过 15 次。
5+
6+ // Space Complexity: O(1)
7+
8+ # include < iostream>
9+ # include < vector>
10+ using namespace std ;
11+
12+ const pair<int , string> valueSymbols[] = {
13+ {1000 , " M" },
14+ {900 , " CM" },
15+ {500 , " D" },
16+ {400 , " CD" },
17+ {100 , " C" },
18+ {90 , " XC" },
19+ {50 , " L" },
20+ {40 , " XL" },
21+ {10 , " X" },
22+ {9 , " IX" },
23+ {5 , " V" },
24+ {4 , " IV" },
25+ {1 , " I" },
26+ };
27+
28+ class Solution {
29+ public:
30+ string intToRoman (int num) {
31+ string roman;
32+ // const auto &[value, symbol]的auto是什么
33+ for (const auto &pair : valueSymbols) {
34+ int value = pair.first ;
35+ const string& symbol = pair.second ;
36+
37+ while (num >= value) {
38+ num -= value;
39+ roman += symbol;
40+ }
41+ if (num == 0 ) {
42+ break ;
43+ }
44+ }
45+ return roman;
46+ }
47+ };
48+
49+ int main () {
50+ Solution s;
51+ int num = 1994 ;
52+ cout << s.intToRoman (num) << endl;
53+ return 0 ;
54+ }
You can’t perform that action at this time.
0 commit comments