zoukankan      html  css  js  c++  java
  • leetcode227 Basic Calculator II

     1 """
     2 Implement a basic calculator to evaluate a simple expression string.
     3 The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
     4 Example 1:
     5 Input: "3+2*2"
     6 Output: 7
     7 Example 2:
     8 Input: " 3/2 "
     9 Output: 1
    10 Example 3:
    11 Input: " 3+5 / 2 "
    12 Output: 5
    13 """
    14 """
    15 这道题因为有空格字符,连续数字字符使得考虑情况有些复杂
    16 为了保存好符号,用了一个sign变量,初始化为'+',保证其正常入栈
    17 """
    18 class Solution:
    19     def calculate(self, s: str) -> int:
    20         if not s:
    21             return '0'
    22         stack = []
    23         sign = '+'  # !!!用一个sign实现将符号后置使用
    24         num = 0
    25         for i in range(len(s)):
    26             if s[i].isdigit():
    27                 num = num * 10 + int(s[i])  # ord(s[i]) - ord('0')
    28             if not s[i].isdigit() and s[i] != ' ' or i == len(s) - 1:
    29                 if sign == '-':  # 注意这里是sign
    30                     stack.append(-num)
    31                 elif sign == '+':
    32                     stack.append(num)
    33                 elif sign == '*':
    34                     stack.append(stack.pop() * num)
    35                 else:  # 因为python里向下取整,-1.5取整为-2
    36                     temp = stack.pop()
    37                     if temp // num < 0 and temp % num != 0:
    38                         stack.append(temp // num + 1)
    39                     else:
    40                         stack.append(temp // num)
    41                 sign = s[i]
    42                 num = 0
    43         res = 0
    44         for j in range(len(stack)):
    45             res += stack[j]
    46         return res
    47 if __name__ == '__main__':
    48     ans = Solution()
    49     s = "14-3/2"
    50     ans.calculate(s)
  • 相关阅读:
    d3.js--04(enter和exit)
    d3.js--03(增删改查)
    d3.js--02(data和datum原理)
    css文件和js文件后面带一个问号----2015-1103
    json_decode()和json_encode()区别----2015-0929
    随记--更新于20150925
    个人火狐插件汇总--20150924
    『jQuery』.html(),.text()和.val()的概述及使用--2015-08-11
    矩阵求导
    傅里叶变换
  • 原文地址:https://www.cnblogs.com/yawenw/p/12427632.html
Copyright © 2011-2022 走看看