ShashwathKamath
ShashwathKamath

Reputation: 31

I am trying to convert String into integer in Kotlin. Positive numbers are working fine, but negative number is creating issue

So I am trying to solve Reverse Polish notation question. I wanted to try out in Kotlin language. I am able to solve this in Java but in Kotlin it is not allowing "-11" to push onto stack. ---code----

import java.util.*

fun reversePolish(tokens: Array<String>):Int{
    var st = Stack<Int>()

    for (token in tokens){
        if(token.all { Character.isDigit(it) }) {
            st.push(token.toIntOrNull())
        }
        else{
            var n2 = st.pop()
            var n1 = st.pop()
            when(token){
                "+" -> st.push(n1 + n2)
                "-" -> st.push(n1 - n2)
                "*" -> st.push(n1 * n2)
                "/" -> st.push(n1/n2)
            }
        }
    }

    return st.pop()
}

fun main() {
    var arr = arrayOf("10","6","9","3","+","-11","*","/","*","17","+","5","+")
    print(reversePolish(arr))
}

Where am I doing it wrong?

Upvotes: 0

Views: 421

Answers (1)

you might want to try this

fun reversePolish(tokens: Array<String>): Int {
    val stack = Stack<Int>()
    tokens.forEach { item ->
        when (item.toIntOrNull()) {
            null -> {
                val secondNumber = stack.pop()
                val firstNumber = stack.pop()
                when (item) {
                    "+" -> stack.push(firstNumber + secondNumber)
                    "-" -> stack.push(firstNumber - secondNumber)
                    "*" -> stack.push(firstNumber * secondNumber)
                    "/" -> stack.push(firstNumber / secondNumber)
                }
            }
            else -> {
                stack.push(item.toInt())
            }
        }
        
    }
    return stack.pop()
}

Upvotes: 1

Related Questions