Home > database >  Leetcode #13 Roman to Integer Javascript
Leetcode #13 Roman to Integer Javascript

Time:12-15

I am currently trying to solve the "Roman to Integer" question on Leetcode.

My code works with roman numerals such as ("III (3)", "V (5)", "X (10)", "C (50)") for some examples. Where my code breaks down is when roman numerals such as ("IV (4)", "IX (9)", "XL (40)").

 let romanNum = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
 let specCases = {"IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900}
 arr.reduce((acc,cur,i) => {
    //check if it is one of the special cases
    let lastTwo = ""
    if (i !== 0) {
        let lastTwo = arr[i-1].concat(cur)
        console.log(lastTwo)
        console.log(Object.keys(specCases))
        console.log(typeof(lastTwo))
    }
    if (lastTwo in specCases) {
        acc = acc - romanNum[arr[i-1]]   specCases[lastTwo]
        return console.log(acc)
    }
    //for non-sepcial cases run the code below
    acc = acc   romanNum[cur]
    return acc
}, 0)

I've also included the relevant pieces of code above. I checked to make sure the "lastTwo" variable was assigned correctly, that the specCases object keys were being accessed correctly, and the typeof(lastTwo) was a string. All of the things I checked above seemed to be correct.

Below is link to the photo the leetcode output when using "IX":

Evaluates to 11 when it should be 9

When running the code, the second conditional statement is not met, and that portion of the code is not ran.

Why is the second condition not being met?

CodePudding user response:

Barmar answered this question:

Change let lastTwo = arr[i-1].concat(cur) to lastTwo = arr[i-1].concat(cur). You're creating a new variable in the scope of the if, not assigning the outer variable.

  • Related