Skip to content

Commit 55207be

Browse files
committed
3
1 parent 8674180 commit 55207be

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

IntegertoRoman/IntegertoRoman.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
string intToRoman(int num) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
char symbol[] = {'I', 'V', 'X', 'L','C', 'D', 'M'};
7+
string result;
8+
int base = 1000;
9+
int d = 6;
10+
while (num) {
11+
int digit = num / base;
12+
appendRoman(digit, result, symbol + d);
13+
d -= 2;
14+
num %= base;
15+
base /= 10;
16+
}
17+
return result;
18+
}
19+
20+
void appendRoman(int n, string& s, char symbol[]) {
21+
assert(n <= 9);
22+
23+
if (n == 0) return;
24+
if (n <= 3) {
25+
s.append(n, symbol[0]);
26+
}
27+
else if (n == 4) {
28+
s.append(1, symbol[0]);
29+
s.append(1, symbol[1]);
30+
}
31+
else if (n <= 8) {
32+
s.append(1, symbol[1]);
33+
s.append(n - 5, symbol[0]);
34+
}
35+
else if (n == 9) {
36+
s.append(1, symbol[0]);
37+
s.append(1, symbol[2]);
38+
}
39+
}
40+
};

0 commit comments

Comments
 (0)