博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode_Basic Calculator II
阅读量:4653 次
发布时间:2019-06-09

本文共 1835 字,大约阅读时间需要 6 分钟。

题目:

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 eval built-in library function.

Credits:

Special thanks to  for adding this problem and creating all test cases.

代码:

class Solution {public:    int calculate(string s) {    stack
st; int result = 0; int i = 0; while(i
='0'&&s.at(i)<='9') { while(i
='0'&&s.at(i)<='9') { sum = sum * 10 + s.at(i)-'0'; i++; } st.push(sum); } else if(i
='0'&&s.at(i)<='9') { while(i
='0'&&s.at(i)<='9') { sum1 = sum1 * 10 + s.at(i)-'0'; i++; } a*=sum1; st.push(a); } } else if(i
='0'&&s.at(i)<='9') { sum1 = sum1 * 10 + s.at(i)-'0'; i++; } a = (int)(a/sum1); st.push(a); } else { i++; } } stack
st1; while(!st.empty()) { st1.push(st.top()); st.pop(); } while(!st1.empty()) { int a = st1.top(); st1.pop(); if(st1.empty()) return a; else { if((char)(st1.top())=='+') { st1.pop(); int temp = st1.top()+a; st1.pop(); st1.push(temp); } else if((char)(st1.top())=='-') { st1.pop(); int temp = a-st1.top(); st1.pop(); st1.push(temp); } } } return st1.top(); }};
方法比较繁琐。。。就这样了。

转载于:https://www.cnblogs.com/sunp823/p/5601419.html

你可能感兴趣的文章
1035等差数列末项计算
查看>>
CDMA鉴权
查看>>
ASP.NET MVC Identity 兩個多個連接字符串問題解決一例
查看>>
过滤器与拦截器区别
查看>>
第二阶段站立会议7
查看>>
JAVA多线程
查看>>
delphi 更改DBGrid 颜色技巧
查看>>
POJ 2031 Building a Space Station
查看>>
面向对象1
查看>>
任意阶幻方(魔方矩阵)C语言实现
查看>>
织梦教程
查看>>
杭电多校 Harvest of Apples 莫队
查看>>
java 第11次作业:你能看懂就说明你理解了——this关键字
查看>>
C/C++心得-结构体
查看>>
函数名作为参数传递
查看>>
apt-get for ubuntu 工具简介
查看>>
数值计算算法-多项式插值算法的实现与分析
查看>>
day8-异常处理与网络编程
查看>>
Python基础-time and datetime
查看>>
Linux epoll 笔记(高并发事件处理机制)
查看>>