码迷,mamicode.com
首页 > 其他好文 > 详细

227. Basic Calculator II

时间:2020-06-13 22:58:15      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:ora   put   ice   ast   sign   text   sum   empty   express   

package LeetCode_227

import java.util.*

/**
 * 227. Basic Calculator II
 * https://leetcode.com/problems/basic-calculator-ii/description/
 *
 * Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces.
The integer division should truncate toward zero.

Example 1:
Input: "3+2*2"
Output: 7

Example 2:
Input: " 3/2 "
Output: 1

Example 3:
Input: " 3+5 / 2 "
Output: 5
 * */
class Solution {
    fun calculate(s: String): Int {
        val n = s.length
        val stack = Stack<Int>()
        var num = 0
        var sign = ‘+‘
        for (i in s.indices) {
            val cur = s[i]
            if (cur.isDigit()) {
                num = num * 10 + (cur.toInt() - ‘0‘.toInt())
            }
            //i==n-1, means when it comes to tail of string, need to do the last calculation.
            if (!cur.isDigit() && cur != ‘ ‘ || i == n - 1) {
                when (sign) {
                    ‘+‘ -> stack.push(num)
                    ‘-‘ -> stack.push(-num)
                    ‘*‘ -> stack.push(stack.pop() * num)
                    ‘/‘ -> stack.push(stack.pop() / num)
                }
                sign = cur
          //reset num after calculation num
= 0 } } return stack.sum() } }

 

227. Basic Calculator II

标签:ora   put   ice   ast   sign   text   sum   empty   express   

原文地址:https://www.cnblogs.com/johnnyzhao/p/13121946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!