Image From LeetCodeImage From LeetCode

今天我們要講解的是 [Roman to integer],這在 LeetCode 算是比較簡單的題目,讓我們一起開始吧!

進來之前請先注意,我的方式不一定完全正確,只是依照我自己的理念進行撰寫,所以如果程式上有什麼更好的解法,歡迎提出見解。

這次題目

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
2
3
Input: s = "III"
Output: 3
Explanation: III = 3.
1
2
3
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
1
2
3
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

1 <= s.length <= 15
s contains only the characters (‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’).
It is guaranteed that s is a valid roman numeral in the range [1, 3999].

自已解法

這是的題目主要是把羅馬字轉換成數字,可以看到他的規則除了對應的數字外累加外,當後方的羅馬字比前面還要大時,必須要當作數值相減,例如 C=100, M=1000CM=1000-100

第一步我們先定義好羅馬字的關係,接著他有提到數字長度會介於1~15之間:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const romanMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
};

if (s.length <= 0 || s.length > 15) return false;
}

接著我們把字串進行分解來一一的分析,並且建立一個結果值,之後累加的數字會放置在result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var romanToInt = function(s) {
const romanMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
};

if (s.length <= 0 || s.length > 15) return false;

let result = 0;
let strList = s.split('');
for(i=0;i<strList.length;i++){
// put the condition in here
}
return result;
}

之後最重要的一步就是比對下一個值是否大於上一個值,可以透過(i+1)來預先查看,結果為是即進行相減,如果不是的話就單純顯示那數字,注意當相減後記得要跳過下一個數字也就是要多一次的i++;

1
2
3
4
5
6
if (romanMap[strList[i+1]] > romanMap[strList[i]]) {
result += (romanMap[strList[i+1]] - romanMap[strList[i]])
i += 1; // That's mean we can skip the next number
} else {
result += romanMap[strList[i]];
}

實作結果

接著把判斷式放進迴圈後,就完成了!

Image From LeetCodeImage From LeetCode