[LeetCode] Roman to Integer - JavaScript
👩🏻💻 質問する
LeetCode #13 Roman to Integer
👩🏻💻 に答える
var romanToInt = function(s) {
const map = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000};
let result = 0;
for(let i = 0; i < s.length; i++) {
const cur = map[s[i]];
const next = map[s[i+1]];
// 로마 숫자 계산 규칙
if(cur < next) {
result -= cur;
} else {
result += cur;
}
}
return result;
};
// ex) s = "LVIII"
// i = 'L', i+1 = 'V'
// cur = 50, next = 5
// result = 0 + 50 = 50
// i = 'V', i+1 = 'I'
// cur = 5, next = 1
// result = 50 + 5 = 55
// i = 'I', i+1 = 'I'
// cur = 1, next = 1
// result = 55 + 1 = 56
// i = 'I', i+1 = 'I'
// cur = 1, next = 1
// result = 56 + 1 = 57
// i = 'I', i+1 = 'I'
// cur = 1, next = 1
// result = 57 + 1 = 58
参考資料-ローマ数字記号Reference
この問題について([LeetCode] Roman to Integer - JavaScript), 我々は、より多くの情報をここで見つけました https://velog.io/@leeeunbin/LeetCode-Roman-to-Integer-JavaScriptテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol