Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include<iostream>
#include<string>
using namespace std;
int main(){
string Progression;
cin>>Progression;
int OpCnt,Priority[100],Value[100],nest,ip,i;
char chr,Operator[100];
OpCnt=0;
Value[0]=0;
nest=0;
//解析処理
for(i=0;i<Progression.length();i++){
chr=Progression[i];
if('0'<=chr&&chr<='9'){
Value[OpCnt]=10*Value[OpCnt]+chr-'0';
}
else if(chr=='+'||chr=='-'||chr=='*'||chr=='/'){
Operator[OpCnt]=chr;
if(chr=='+'||chr=='-'){
Priority[OpCnt]=nest+1;
}
else{
Priority[OpCnt]=nest+2;
}
OpCnt++;
Value[OpCnt]=0;
}
else if(chr=='('){
nest+=10;
}
else if(chr==')'){
nest-=10;
}
}
//計算処理
while(OpCnt>0){
ip=0;//計算優先度の一番高い値を示す
for(i=1;i<OpCnt;i++){
if(Priority[ip]<Priority[i]){
ip=i;
}
}
chr=Operator[ip];
if(chr=='+'){
Value[ip]=Value[ip]+Value[ip+1];
}
else if(chr=='-'){
Value[ip]=Value[ip]-Value[ip+1];
}
else if(chr=='*'){
Value[ip]=Value[ip]*Value[ip+1];
}
else if(chr=='/'){
Value[ip]=Value[ip]/Value[ip+1];
}
for(i=ip+1;i<OpCnt;i++){
Value[i]=Value[i+1];
Operator[i-1]=Operator[i];
Priority[i-1]=Priority[i];
}
OpCnt--;
}
cout<<Value[0]<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment