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.
/*
已知条件:
1.只包含空格,+,-,(,),非负整数
2.假设输入一定合法
测试用例
"6-(4-9)+7"
"8+(1+(4+5-(7-3)-2)-3)+(6+8)"
"1 + 1+2"
用括号分割表达式,遇到()先算括号表达式内容
*/
class Solution {
public:
int calculate(string &s ,int& start,int end)
{
char pre_op='+';
int num=,res=;
while(start<end){
if(s[start]==' '){
start++;continue;
}
if(isdigit(s[start])){
num = num*+(s[start++]-'');
}else if(s[start]=='('){
num = calculate(s,++start,end);
start++;
}else if(s[start]==')'){
return pre_op=='+' ? res+num:res-num;
}else{
res = pre_op=='+' ? res+num:res-num;
pre_op = s[start++];
num = ;
}
}
return pre_op=='+' ? res+num:res-num;
}
int calculate(string s) {
int start = ;
return calculate(s,start,s.size());
}
};
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.
/*
题目已知:
1.只包含非负整数,加减乘除,空格
2.假设输入一直合法
涉及的几个点:
1.数字分割
2.字符串转整数
3.运算符的优先级
可能隐藏的点:
大数
测试案例:
"0"
"1+0"
"1+10"
" 13 + 24 "
" 23+ 34*3 /2 "
" 12 - 7*3/2 + 35/7-3 "
" 7*2/3 + 9"
"12 - 7*3/2 + 35/7"
*/
class Solution {
public:
int calculate(string s) {
int size = s.size();
long long int exp_res = ,res=;
long int num =;
char pre_op='+';
for(int i=;i<size;i++){
if(s[i]==' ') continue;
if(isdigit(s[i])){
num = num*+(s[i]-'');
if(i+ == size || !isdigit(s[i+])){//如果下一个位置是最后一个位置,或者下一个位置不是数字了
if(pre_op=='+'){
exp_res = num;
}else if(pre_op=='-'){
exp_res = -num;
}else if(pre_op=='*'){
exp_res *= num;
}else{
exp_res /= num;
}
}
}else{
if(s[i]=='+' || s[i]=='-'){
res += exp_res;
}
pre_op = s[i];
num=;
}
}
return res+exp_res;
}
};