[LeetCode] 13. Roman to Integer
Cathy P

題目

難度:Easy

LeetCode 連結:
https://leetcode.com/problems/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 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 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.

題目有點長,簡單來說就是要把羅馬符號數字轉換成阿拉伯數字。

解題過程

羅馬數字有一個特徵:

1.當羅馬符號的數值呈現降冪時,只要把每個羅馬符號數值加總就是答案。
Example 1:

1
2
3
Input: s = "III"
Output: 3
Explanation: 為降冪排列:I=1,1 + 1 + 1 = 3

Example 2:

1
2
3
4
Input: s = "LVIII"
Output: 58
Explanation: 為降冪排列:L = 50, V = 5, III = 3,
50 + 5 + 3 = 58

2.當數值比較小的羅馬符號出現在左邊時,該數值會加上一個負號。

Example 3:

1
2
3
4
5
6
7
8
9
10
11
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, C = 100, X = 10, V = 5, I =1.
M = 1000
C 出現在比他大的M(1000)左邊 = -100
M = 1000
X 出現在比他大的C(100)左邊 = -10
C = 100
I 出現在比他大的V(5)左邊 = -1
V = 5
1000 - 100 + 1000 - 10 + 100 - 1 + 5 = 1994

所以我們只需判斷 n+1 比 n 大還是小,就能判斷 n 的正負值。

程式:

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

let sum = 0
for(let i=0; i<s.length-1; i++){
if(roman[s[i]] >= roman[s[i+1]]){
sum += roman[s[i]];
}
else{
sum -= roman[s[i]];
}
}
sum += roman[s[s.length-1]];
return sum
};

複雜度

時間複雜度:O(N)
空間複雜度:O(1)