|
1 | | -# leetcode-roman-to-integer |
2 | | -Leetcode.com Roman to Integer PHP Solution |
| 1 | +# Leetcode Roman to Integer |
| 2 | +Leetcode.com Roman to Integer PHP Solution |
| 3 | +<https://leetcode.com/problems/roman-to-integer/> |
| 4 | + |
| 5 | +### Problem |
| 6 | +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. |
| 7 | + |
| 8 | +| Symbol | Value | |
| 9 | +|--------|-------| |
| 10 | +| I | 1 | |
| 11 | +| V | 5 | |
| 12 | +| X | 10 | |
| 13 | +| L | 50 | |
| 14 | +| C | 100 | |
| 15 | +| D | 500 | |
| 16 | +| M | 1000 | |
| 17 | + |
| 18 | +For example, `2` is written as `II` in Roman numeral, just two ones added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. |
| 19 | + |
| 20 | +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: |
| 21 | +- `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. |
| 22 | +- `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. |
| 23 | +- `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. |
| 24 | + |
| 25 | +### Constraints |
| 26 | +- `1 <= s.length <= 15` |
| 27 | +- `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M').` |
| 28 | +- It is guaranteed that `s` is a valid roman numeral in the range `[1, 3999]`. |
| 29 | + |
| 30 | +### Solution |
| 31 | +```PHP |
| 32 | +class Solution { |
| 33 | + function romanToInt($s) { |
| 34 | + $romans = array( |
| 35 | + 'M' => 1000, |
| 36 | + 'CM' => 900, |
| 37 | + 'D' => 500, |
| 38 | + 'CD' => 400, |
| 39 | + 'C' => 100, |
| 40 | + 'XC' => 90, |
| 41 | + 'L' => 50, |
| 42 | + 'XL' => 40, |
| 43 | + 'X' => 10, |
| 44 | + 'IX' => 9, |
| 45 | + 'V' => 5, |
| 46 | + 'IV' => 4, |
| 47 | + 'I' => 1, |
| 48 | + ); |
| 49 | + $roman = 'III'; |
| 50 | + $result = 0; |
| 51 | + |
| 52 | + foreach ($romans as $key => $value) { |
| 53 | + while (strpos($roman, $key) === 0) { |
| 54 | + $result += $value; |
| 55 | + $roman = substr($roman, strlen($key)); |
| 56 | + } |
| 57 | + } |
| 58 | + return $result; |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
0 commit comments