Basic Calculator,Basic Calculator II

时间:2022-07-08 06:45:27
一.Basic Calculator
Total Accepted: 18480 Total Submissions: 94750 Difficulty: Medium

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());
}
};
 
二.Basic CalculatorII
Total Accepted: 14291 Total Submissions: 64507 Difficulty: Medium

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;
}
};