[華為機試真題]68.簡單四則運算
阿新 • • 發佈:2019-02-10
題目
輸入一個只包含個位數字的簡單四則運算表示式字串,計算該表示式的值
注:
3.1、表示式只含 +, -, *, / 四則運算子,不含括號
3.2、表示式數值只包含個位整數(0-9),且不會出現0作為除數的情況
3.3、要考慮加減乘除按通常四則運算規定的計算優先順序
3.4、除法用整數除法,即僅保留除法運算結果的整數部分。比如8/3=2。輸入表示式保證無0作為除數情況發生
3.5、輸入字串一定是符合題意合法的表示式,其中只包括數字字元和四則運算子字元,除此之外不含其它任何字元,不會出現計算溢位情況
要求實現函式
int calculate(int len,char *expStr) 【輸入】 int len: 字串長度;char *expStr: 表示式字串; 【輸出】 無 【返回】 計算結果
示例
1)輸入:char *expStr = “1+4*5-8/3”
函式返回:19
2)輸入:char *expStr = “8/3*3”
函式返回:6
思路
題目要求很簡單,只是計算個位數的四則運算,且沒有括號。主要考察棧的運用,實現時採用兩個輔助棧,一個用來存放運算元,一個用來存放運算子。根據操作符的優先順序進行計算。
兩個陣列分別儲存運算元和操作符,掃描輸入的字串,當遇到*和/的時候,邊計算邊儲存,將計算結果存到運算元的陣列中,當遇到+和-號時只儲存不計算。當所有資料儲存完畢後,因為運算就只剩下+-運算了.
程式碼
/*---------------------------------------
* 日期:2015-07-07
* 作者:SJF0115
* 題目:簡單四則運算
* 來源:華為機試真題
-----------------------------------------*/
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
// 簡單四則運算
int calculate(string str){
int size = str.size();
if(size == 0){
return 0;
}//if
// 數字棧
stack<int> num;
// 運算子棧
stack <char> op;
for(int i = 0;i < size;++i){
// 數字
if(str[i] >= '0' && str[i] <= '9'){
num.push(str[i] - '0');
}//if
// 運算子 加減
else if(str[i] == '+' || str[i] == '-'){
op.push(str[i]);
}//else
// 運算子 乘除
else{
char o = str[i];
int a = num.top();
num.pop();
int b = str[++i] - '0';
if(o == '*'){
num.push(a * b);
}//if
else if(o == '/'){
num.push(a / b);
}//else
}//else
}//for
// 加減操作
while(!op.empty()){
char o = op.top();
op.pop();
int a = num.top();
num.pop();
int b = num.top();
num.pop();
if(o == '+'){
num.push(a + b);
}//if
else if(o == '-'){
num.push(b-a);
}//else
}//while
return num.top();
}
int main(){
string str;
//freopen("C:\\Users\\Administrator\\Desktop\\acm.txt","r",stdin);
while(cin>>str){
cout<<calculate(str)<<endl;
}//while
return 0;
}