zoukankan      html  css  js  c++  java
  • 227. Basic Calculator II

    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

    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
            """
            op = '+'
            n = 0
            l = []
            for i in range(len(s)):
                if s[i].isdigit():
                    n = n *10 +int(s[i])
                if not s[i].isdigit() and not s[i].isspace() or i == len(s)-1:
                    if op == '+':
                        l.append(n)
                    if op == '-':
                        l.append(-n)
                    if op == '*':
                        a = l.pop()*n
                        l.append(a)
                    if op == '/':
                        a = int(l.pop()/n)
                        l.append(a)
                    op = s[i]
                    n = 0
            num = 0
            while len(l):
                num += l.pop()
            return num
    
  • 相关阅读:
    Hive 使用问题集锦
    scala def/val/lazy val区别以及call-by-name和call-by-value
    spark学习流程
    Hadoop
    Hive
    Chrome快捷键
    Java API帮助文档
    Java 访问修饰符与非访问修饰符
    java 关键字
    Solr配置Ikanalyzer分词器
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9733363.html
Copyright © 2011-2022 走看看