Basic Calculator II
2015-08-23 20:44
169 查看
题目:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
Note: Do not use the
library function.
解题思路:
类似于Basic Calculator I。代码如下:
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def cal(num1,num2,op):
if op=='+':
return num1+num2
elif op=='-':
return num1-num2
elif op=='*':
return num1*num2
elif op=='/':
return num1/num2
def readNum(s,index):
res = 0
while s[index] in '0123456789':
res = 10*res+int(s[index])
index = index+1
return res,index
map = {'$':0, '+':1, '-':1, '*':2, '/':2}
operator, operand = ['$'], []
s = ''.join((s+'$').split())
index = 0
while len(operator)!=0:
i = s[index]
if i not in '+-*/$':
num ,index= readNum(s,index)
operand.append(num)
else:
if i=='$' and operator[len(operator)-1]=='$':
return operand.pop()
elif map[i]>map[operator[len(operator)-1]]:
operator.append(i)
index += 1
else:
num1,num2 = operand.pop(), operand.pop()
num = cal(num2,num1,operator.pop())
operand.append(num)
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.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the
evalbuilt-in
library function.
解题思路:
类似于Basic Calculator I。代码如下:
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def cal(num1,num2,op):
if op=='+':
return num1+num2
elif op=='-':
return num1-num2
elif op=='*':
return num1*num2
elif op=='/':
return num1/num2
def readNum(s,index):
res = 0
while s[index] in '0123456789':
res = 10*res+int(s[index])
index = index+1
return res,index
map = {'$':0, '+':1, '-':1, '*':2, '/':2}
operator, operand = ['$'], []
s = ''.join((s+'$').split())
index = 0
while len(operator)!=0:
i = s[index]
if i not in '+-*/$':
num ,index= readNum(s,index)
operand.append(num)
else:
if i=='$' and operator[len(operator)-1]=='$':
return operand.pop()
elif map[i]>map[operator[len(operator)-1]]:
operator.append(i)
index += 1
else:
num1,num2 = operand.pop(), operand.pop()
num = cal(num2,num1,operator.pop())
operand.append(num)
相关文章推荐
- ROM、SDRAM、RAM、DRAM、SRAM、FLASH 的区别
- 哪个效率更高?x=x+1, x+=1, x++
- Oracle 游标使用全解
- 数据结构之---C语言实现拓扑排序AOV图
- android 手势识别(一)
- Deep Learning及NLP(自然语言处理)杂谈--第三部分
- Deep Learning及NLP(自然语言处理)杂谈--第二部分
- 黑马程序员 --- OC中的类
- 【BZOJ1212】【HNOI2004】L语言
- ThinkPHP3.1.3部署到SAE 教程
- CCActionGird3D源码解析
- Linux 经常使用 性能 检测 命令 说明
- HDU 4407 Sum(容斥原理)
- POJ 1321 棋盘问题(深搜)
- [GDOI模拟2015.08.18]解密
- C/C++头文件注释
- 坚持不懈之linux haproxy 配置文件 详情
- windows 10 设置
- 位扩展和位截断
- [LeetCode] Search a 2D Matrix(二分查找)