問題:
把羅馬數字轉成阿拉伯數字
範例:
1. 輸入: s ="III" 輸出: 3
2. 輸入: s ="LVIII" 輸出: 58
3. 輸入: s ="MCMXCIV" 輸出: 1994
提問:
沒有,也許可以問一些羅馬數字的規則,像是羅馬數字有零嗎? 有最高上限嗎?
一般想法:
看要從右往左疊加,還是要從左往右,都一樣,從右往左簡單一些。
進階解法:
沒有
程式:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var romanToInt = function (s) { | |
let number = 0 | |
let prev = 0 | |
const table = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000, | |
} | |
for (let i = 0; i < s.length; i++) { | |
let char = table[s.charAt(i)]; | |
if (char > prev) { | |
number = number + char - prev * 2; | |
} else { | |
number = number + char; | |
} | |
prev = char; | |
} | |
return number; | |
}; |
文章標籤
全站熱搜