LeetCode每日一练【13】

LeetCode -- Roman to Integer

数组比较法

思路:

  1. 将所有罗马数字字符对应的数字存储到数组arr
  2. 循环比较数组元素, 当数组arr[i+1]的值比arr[i]的值大时, 证明是组合罗马字符(后一个罗马字符的数字减去前一个罗马字符对应的数字),先进行减法计算后,再加法赋值到res中; 反之,直接进行加法赋值到res
  3. 返回最终结果res
/*
 * @Author: fox
 * @Date: 2022-04-29 16:25:29
 * @LastEditors: fox
 * @LastEditTime: 2022-04-29 19:06:41
 * @Description: https://leetcode.com/problems/roman-to-integer/
 */

const Roman = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000,  
};

/**
 * @param {string} s 罗马数字
 * @return {number} 阿拉伯数字
*/
const romanToInt = (s) => {
    const arr = [];
    let res = 0;
    for (const i of s) {
        arr.push(Roman[i])
    };

    for (let i = 0; i < arr.length; i++) {
        if (arr[i + 1] > arr[i]) {
            res += (arr[i + 1] - arr[i])
            i++
        } else {
            res += arr[i]
        }   
    };

    return res;
};

let value;

value = "III";
console.log(romanToInt(value)); // 3

value = "LVIII";
console.log(romanToInt(value)); // 58

value = "MCMXCIV";
console.log(romanToInt(value)); // 1994

posted @ 2022-04-29 19:17  白い故雪  阅读(13)  评论(0编辑  收藏  举报