1,题目要求
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.
实现基本计算器来评估简单的表达式字符串。
表达式字符串仅包含非负整数,+, - ,*,/运算符和空格。 整数除法应截断为零。
注意:
您可以假设给定的表达式始终有效。
不要使用eval内置库函数。
2,题目思路
对于这道题,要求获得一个基本数字运算的字符串的计算结果。
题目中给出的字符串,是一个只含有加减乘除的计算式,因此,在读取的字符串的过程中,可以利用istringstream,一般来说,如果只是读取字符,那么是利用空格进行分隔的。
而如果是不同的数据类型,则是按照数据类型进行读取的。
例子:
string s = "+3/22+1+";
istringstream in(s);
char op;
int num;
while(in >> op){
cout<<op<<endl;
in>>num;
cout<<num<<endl;
}
在这道题上,我们为了方便读取,我们在字符串的最前和最后都加上’+’,方便进行读取。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int calculate(string s) {
istringstream in('+' + s + '+');
int total = 0;
int num = 0;
int n = 0;
char op;
while(in >> op){
if(op == '+'){
total += num;
in >> num;
}
else if(op == '-'){
total += num;
in >> num; //获得该符号之后的处理对象
num = -num;
}
else if(op == '*'){
in >> n;
num *= n;
}
else{
in >> n;
num /= n;
}
}
return total;
}
};