224、Basic Calculator
2024-08-23 01:37:27
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 .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
这个题目的思路要考虑的情况比较多,主要的想法是:符号相当于数字之前的正负号;默认在第一个数字之前加了正号。
有一个基准result为0,可能有5种情况:
/*
1、如果是数字,就转换为十进制;考虑123+122等(isdigit函数);
2、如果是+号,用result去和上一个符号(sign)和数字(number)运算,然后将number清空,符号'+'保存;
3、'-'同上;
4、如果是'('那么利用一个栈,将之前的结果result保存,将'('前的符号sign保存;然后将result和sign初始化(类似于重新开始计算);
5、如果是')'那么这个括号中的result要和之前保存的result(stack)还有sign(stack)进行计算。
*/
1 int calculate(string s) {
2 long int result=0;
3 stack<long int> s1;
4 int sign=1,i=0;
5 int number=0;
6 // 2+1+(4+5+2)-3+7
7 while(i<s.size())
8 {
9 //123
10 if(isdigit(s[i]))
11 {
12 number=number*10+(s[i]-'0');
13 }
14 else if(s[i]=='+')
15 {
16 result+=sign*number;
17 sign=1;
18 number=0;
19 }
20 else if(s[i]=='-')
21 {
22 result+=sign*number;
23 sign=-1;
24 number=0;
25 }
26 else if(s[i]=='(')
27 {
28 s1.push(result);
29 s1.push(sign);
30 result=0;
31 sign=1;
32 }
33 //符号是括号中result前的正负号。
34 else if(s[i]==')')
35 {
36 result+=sign*number;
37 //非常重要
38 number=0;//否则括号前一个数字要被计算两次。
39 long temp=s1.top();
40 s1.pop();
41 result*=temp;
42 result+=s1.top();
43 s1.pop();
44 }
45 i++;
46 }
47 result+=sign*number;//每次遇到下一个符号即数字后一个符号,才去算上一个数字及其前面的正负号。
48 return result;
49 }
50 };
最新文章
- (原) 2.1 Zookeeper原生API使用
- SpaceSniffer 硬盘透视软件
- mvc3升级mvc4的方法记录.
- JavaScript 中的 this ,看着一篇就够了
- jquery html 动态添加元素绑定事件
- 学会爱上iOS自动布局(Auto Layout) - 剑尖
- 谈一下spring 的理解
- Java Interface,反射
- 微积分入门(";SX";T版)
- Django(五)母版继承、Cookie、视图装饰器等
- 奖品列表组件【仿swiper】
- windows 下面安装make
- Linux集群架构(一)
- 【Leetcode】无重复字符的最长子串
- 鸟哥Linux私房菜基础学习篇学习笔记1
- nginx并发模型与traffic_server并发模型简单比较
- Codeforces Round #371 (Div. 1) D. Animals and Puzzle 二维倍增
- 【转】Qt在pro中设置运行时库MT、MTd、MD、MDd,只适合VS版本的Qt
- JQuery - Tab Control
- thinkphp5.0Traits引入
热门文章
- HTML常用标签(上)
- pytest文档33-Hooks函数获取用例执行结果(pytest_runtest_makereport)
- npoi 设置单元格格式
- 安装JDK及环境变量配置
- spring cloud:搭建基于consul的服务提供者集群(spring cloud hoxton sr8 / spring boot 2.3.4)
- centos8上配置openresty/nginx可访问php
- VScode如何配置c/c++运行环境
- java中true是关键字吗
- vue学习笔记(一)---- vue指令( v-bind 属性绑定 )
- 【Azure Developer】使用.Net Core解析JSON的笔记