Day 3: From string to math

apomalyn

Xavier Chretien

Posted on January 8, 2020

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
💖 💪 🙅 🚩
apomalyn
Xavier Chretien

Posted on January 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 3: From string to math
challenge Day 3: From string to math

January 8, 2020

Day 2: Fixed point
challenge Day 2: Fixed point

January 7, 2020

31 days of problems
challenge 31 days of problems

January 6, 2020