keep learning, keep coding!
Problem - Roman to Integer
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 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.
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 before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
翻譯蒟蒻
將羅馬數字轉換為數字。
Example 1:
1
2
3Input: s = "III"
Output: 3
Explanation: III = 3.Example 2:
1
2
3Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.Example 3:
1
2
3Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Solution - JavaScript
1 | /** |
在 JavaScript 中,沒有明確判定 nextValue 是否存在的原因是在 JavaScript 中,如果你嘗試存取不存在的索引,不會引發錯誤,而是回傳 undefined。因此,在存取 s[i + 1] 時,如果 i + 1 超出了字串的長度,將傳回 undefined。
Solution - Ruby
1 | def roman_to_int(s) |
在 Ruby 裡要去判定 next_value 是否存在,因為如果沒有判斷就會引發 comparison of Integer with nil failed (ArgumentError) in solution.rb (<),我們要確定有下一個字母可以比較之後,再去做加總。