source: https://leetcode.com/problems/integer-to-roman/
C/C++ Solution to LeetCode problem 12. Integer to Roman.
Problem
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, 2
is written as II
in Roman numeral, just two one’s added together. 12
is written as XII
, which is simply X + II
. The number 27
is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.
Examples
Example 1:
Input: num = 3
Output: “III”
Explanation: 3 is represented as 3 ones.
Example 2:
Input: num = 58
Output: “LVIII”
Explanation: L = 50, V = 5, III = 3.
Example 3:
Input: num = 1994
Output: “MCMXCIV”
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints
1 <= num <= 3999
Solution
We store the roman simbols in a hash table using its value as key.
- The we will get the last digit of the number (using module) and convert it to roman.
- We have 6 cases:
- If digit is
0
. - If
1 <= digit <= 3
. - If digit is
4
. - If digit is
5
. - If
6 <= digit <= 8
. - If digit is
9
.
- If digit is
- We generate the respective roman number (multipliying the digit by its position, 1, 10, 100, 1000).
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
class Solution {
public:
string intToRoman(int num) {
unordered_map<int, char> roman;
roman[1] = 'I';
roman[5] = 'V';
roman[10] = 'X';
roman[50] = 'L';
roman[100] = 'C';
roman[500] = 'D';
roman[1000] = 'M';
string str = ""s;
int tmp = num;
int p = 1;
while (tmp != 0) {
int d = tmp % 10;
if (d == 0) {
} else if (d <= 3) {
for (int i=0; i<d; i++)
str = roman[1 * p] + ""s + str;
} else if (d == 4)
str = roman[1 * p] + ""s + roman[5 * p] + str;
else if (d == 5)
str = roman[5 * p] + str;
else if (d > 5 && d < 9) {
string t = "";
for (int i=0; i< (d-5); i++)
t += roman[1 * p];
str = roman[5 * p] + t + str;
}
else
str = roman[1 * p] + ""s + roman[10 * p] + str;
tmp /= 10;
p *= 10;
}
return str;
}
};