224. Basic Calculator

224. Basic Calculator,第1张

概述Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spa

Implement a basic calculator to evaluate a simple Expression string.

The Expression string may contain open ( and closing parentheses ),the plus + or minus sign -,non-negative integers and empty spaces .

Example 1:

input: "1 + 1"
Output: 2

Example 2:

input: " 2-1 + 2 "
Output: 3

Example 3:

input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

Note:

You may assume that the given Expression is always valID.Do not use the eval built-in library function.
class Solution:    def calculate(self,s):        """        :type s: str        :rtype: int        """        num,sign,i = 0,1,0        op = []        while i <len(s):            if s[i].isdigit():                start = i                while i<len(s) and s[i].isdigit():                    i += 1                n = int(s[start:i])                num += n * sign                continue            if s[i]==‘+‘:                sign = 1                i += 1                continue            if s[i]==‘-‘:                sign = -1                i += 1                continue            if s[i]==‘(‘:                op.append(num)                op.append(sign)                num = 0                sign = 1                i += 1                continue            if s[i]==‘)‘:                num = num * op.pop()                num += op.pop()                i += 1                continue            i += 1        return num
总结

以上是内存溢出为你收集整理的224. Basic Calculator全部内容,希望文章能够帮你解决224. Basic Calculator所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1234647.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存