leetcode刷题笔记 227题 基本计算器II

leetcode刷题笔记 227题 基本计算器II

源地址:227. 基本计算器 II

问题描述:

实现一个基本的计算器来计算一个简单的字符串表达式的值。

字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。

示例 1:

输入: "3+2*2"
输出: 7
示例 2:

输入: " 3/2 "
输出: 1
示例 3:

输入: " 3+5 / 2 "
输出: 5
说明:

你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。

//与224题思路一致 注意分割符号与数字
//默认符号为+
//以 3 + 2 * 5 为例转换为 +3+2*5 转换为 3+ 2+ 5*
//通过sign计算上一个符号
import scala.collection.mutable
object Solution {
    def calculate(s: String): Int = {
        //变量定义
        val stack = new mutable.Stack[Int]()
        var operand = 0
        var res = 0
        var sign = '+'
        //去除空格
        val str = s.replace(" ", "")
        
        for (i <- 0 to str.length-1) {
            val ch = str.charAt(i)
            if (ch.isDigit == true) {
                operand = operand * 10 + (ch - '0').toInt
            }
            if (ch.isDigit == false || i == str.length-1) { 
                //println("operand: " + operand)
                if (sign == '+') stack.push(operand)
                if (sign == '-') stack.push(operand * (-1))
                if (sign == '*') {
                    stack.push(stack.pop() * operand)
                }
                if (sign == '/') {
                    stack.push(stack.pop() / operand)
                }
                operand = 0
                sign = ch
            }    
        }
        
        //栈内元素出栈 求和
        while (stack.size > 0){
            val temp = stack.pop()
            res += temp
        }
        return res 
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13814046.html