觀前提醒:
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, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven 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.Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
可參考以下圖片(來源:Hua Hua)
map
來儲存羅馬符號跟數字之間的對應關係,在一般的情況下(ex. III, VI),可以直接將羅馬符號轉換成數字。IV,XC
這種組合,就要另外處理,這種組合的特色是後面的符號會大於前面的符號
,且數字會變成從後一字元,減去前一字元。(“ab” pattern, b is larger than a)(The value changes from a+b to b-a)/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
let sum = 0;
let preChar = "";
for (let currChar of s) {
sum += map[currChar];
if (preChar !== "" && map[currChar] > map[preChar]) {
sum -= 2 * map[preChar];
}
preChar = currChar;
}
return sum;
};
這題也是一開始我覺得簡單,先建立好 map,然後只要把字串從左到右所對應的數值,通通加總起來就能收工。
但後來實作才發現,有一個很不好解決的地方。就是那 IV (4)、IX (9) 、IC(99)
這類的,這是右邊的數字扣除左邊的數字來實現的。我也是看了花花大的影片,才天靈蓋一拍想到還能用 "a+b後,減去兩倍 a,得到 b-a"
這種方式,來達到同樣效果。真的太猛啦XD
謝謝大家的收看,LeetCode 小學堂我們下次見~