DEV Community

Xavier Chretien
Xavier Chretien

Posted on

1 2

Day 3: From string to math

Details

  • Difficulty: Hard
  • Programming language: Kotlin

Problem

Giving a string consisting of parentheses, single digits, positive and negative signs,
convert the string into a mathematical expression to obtain the answer.

Don't use eval or a similar built-in parser.

For example:

  • Given -1+(2+3), you should return 4

Solution

Before looking at my solution, which is probably not the best, why don't you give it a try? 😁

I decide to simply use a simple switch case (when in Kotlin)

/**
 * Parse and calculate the string passed in param
 *
 * @param calculation
 * @return result of the calculation
 */
fun parseAndCalculation(calculation: String): Int {
    var result = 0

    var multiplier = 1
    var subProblem = -1

    for ((index, c) in calculation.withIndex()) {
        if(subProblem == -1 || c != ')')
            when(c) {
                '+' -> multiplier = 1
                '-' -> multiplier = -1
                '(' -> subProblem = index
                ')' -> {
                    result += multiplier * parseAndCalcul(calculation.substring(subProblem + 1, index))
                    subProblem = -1
                }
                else -> result += multiplier * c.toString().toInt()
            }
    }

    return result
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (3)

Collapse
 
nickholmesde profile image
Nick Holmes

Nice solution to the problem, but you can simplify. Addition is associative, e.g.

a+(b+c) = (a+b)+c = a+b+c

(Subtraction is trivially changed to addition 2 - 1 = 2 + -1. I see you have understood this).

As the parenthesis don't do anything, you can just ignore them. (I would set up a range a characters to ignore, and add whitespace to it as well)

I've got to go to a meeting now, but I'll post an F# version later - might be able to get it down to a single expression.

Collapse
 
apomalyn profile image
Xavier Chretien

Oh! Really good idea, thank you 😃 I will try this. I don't have really looked into the different types of class there is in Kotlin. Thank you !

Collapse
 
nickholmesde profile image
Nick Holmes

Indeed. :-(

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay