November 15, 2023

Viiisit [LeetCode] - 13. Roman to Integer

#javascript#ruby

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.

翻譯蒟蒻

將羅馬數字轉換為數字。


Solution - JavaScript

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
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const romanChar = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}

let totalValue = 0;

for (let i = 0; i < s.length; i++) {
let char = s[i];
let nextChar = s[i+1];
let value = romanChar[char];
let next_value = romanChar[nextChar]

if (value < next_value) {
totalValue -= value;
} else {
totalValue += value;
}
}

return totalValue;
};

在 JavaScript 中,沒有明確判定 nextValue 是否存在的原因是在 JavaScript 中,如果你嘗試存取不存在的索引,不會引發錯誤,而是回傳 undefined。因此,在存取 s[i + 1] 時,如果 i + 1 超出了字串的長度,將傳回 undefined。

Solution - Ruby

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
def roman_to_int(s)
roman_char = {
"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000
}

total_value = 0

s.each_char.with_index do |char, i|
value = roman_char[s[char]]
next_value = roman_char[s[i+1]]

# 判斷 next_value 是否存在
if next_value && value < next_value
total_value -= value
else
total_value += value
end
end

total_value
end

在 Ruby 裡要去判定 next_value 是否存在,因為如果沒有判斷就會引發 comparison of Integer with nil failed (ArgumentError) in solution.rb (<),我們要確定有下一個字母可以比較之後,再去做加總。

LeetCode 傳送門 - Roman to Integer