8000 added solution to integer to roman · dotmarn/algorithm-solution@b14c491 · GitHub
[go: up one dir, main page]

Skip to con 10000 tent

Commit b14c491

Browse files
committed
added solution to integer to roman
1 parent 4e054b2 commit b14c491

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

Integer to Roman/index.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
class Solution {
4+
function intToRoman($num) {
5+
6+
$num_to_convert = intval($num);
7+
8+
$res = '';
9+
10+
$data = [
11+
'M' => 1000,
12+
'CM' => 900,
13+
'D' => 500,
14+
'CD' => 400,
15+
'C' => 100,
16+
'XC' => 90,
17+
'L' => 50,
18+
'XL' => 40,
19+
'X' => 10,
20+
'IX' => 9,
21+
'V' => 5,
22+
'IV' => 4,
23+
'I' => 1
24+
];
25+
26+
foreach ($data as $key => $value) {
27+
28+
$matches = intval($num_to_convert / $value);
29+
30+
if ($matches !== 0) {
31+
$res .= str_repeat($key, $matches);
32+
}
33+
34+
$num_to_convert %= $value;
35+
36+
if ($num_to_convert === 0) {
37+
return $res;
38+
}
39+
}
40+
41+
return $res;
42+
}
43+
}

Integer to Roman/question.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
2+
3+
```
4+
Symbol Value
5+
I 1
6+
V 5
7+
X 10
8+
L 50
9+
C 100
10+
D 500
11+
M 1000
12+
```
13+
14+
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.
15+
16+
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:
17+
18+
I can be placed before V (5) and X (10) to make 4 and 9.
19+
X can be placed before L (50) and C (100) to make 40 and 90.
20+
C can be placed before D (500) and M (1000) to make 400 and 900.
21+
22+
### Example 1
23+
```
24+
Input: num = 3
25+
Output: "III"
26+
Explanation: 3 is represented as 3 ones.
27+
```
28+
29+
### Example 2
30+
```
31+
Input: num = 58
32+
Output: "LVIII"
33+
Explanation: L = 50, V = 5, III = 3.
34+
```
35+
36+
### Example 3
37+
```
38+
Input: num = 1994
39+
Output: "MCMXCIV"
40+
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
41+
```

0 commit comments

Comments
 (0)
0