Prefix notation string calculator Javascript problem

530 Views Asked by At

I'm making a calculator for a prefix notation string and it has covered all the normal tests that I've added to it. But I've come across one that it doesn't seem to be getting the right answer for and I'm unsure of why it seems to be having a problem with this.

I think it might have something to do with the division and subtraction when it comes to the numbers, because apart of the problem was I needed to assume that all inputs were valid, so there wouldn't be negative numbers nor would there be bad inputs IE not formatted correctly.

Here is the code and some of the test problems I inputted into it.

"+ / * 1 3 + 12 16 * 10 4" = 40.107142857142854
"+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4" = 24.00267857142857 --- This is the one it doesn't like
"/ 300000 * + 12 16 * 10 40"= 26.785714285714285
function prefixEval(expression) {
    let temp = expression.split(' ')
    let expr = temp.reverse()
    let stack = []

    for (let i = 0; i < expr.length; i++) {
        if (
            expr[i] === '+' ||
            expr[i] === '-' ||
            expr[i] === '/' ||
            expr[i] === '*'
        ) {
            let j = stack.pop()
            let k = stack.pop()
            let temp = checkOperator(parseInt(j), parseInt(k), expr[i])

            stack.push(temp)
        } else {
            stack.push(expr[i])
        }
    }
    return stack
}

function checkOperator(a, b, op) {
    switch (op) {
        case '+':
            console.log('adding' + ' ' + a + ' ' + op + ' ' + b)
            console.log(a + b)
            return a + b
        case '-':
            console.log('subtracting' + ' ' + a + ' ' + op + ' ' + b)
            console.log(a - b)
            return a - b
        case '/':
            console.log('dividing' + ' ' + a + ' ' + op + ' ' + b)
            console.log(a / b)
            return a / b
        case '*':
            console.log('multiplying' + ' ' + a + ' ' + op + ' ' + b)
            console.log(a * b)
            return a * b
        default:
            return 'this is not correct'
    }
}

console.log(prefixEval('+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4'))
1

There are 1 best solutions below

0
On BEST ANSWER

You are using parseInt and dividing 2 by 0 which produces Infinity . To fix,

Change,

let temp = checkOperator(parseInt(j), parseInt(k), expr[i])

to

let temp = checkOperator(parseFloat(j), parseFloat(k), expr[i])

This is give you the expected answer