#include<bits/stdc++.h>
using namespace std;
int StoI(string t)
{
stringstream sin;
sin<<t;
int d;
sin>>d;
return d;
}
string ItoS(int d)
{
stringstream sin;
sin<<d;
string t;
sin>>t;
return t;
}
int findOp(string t, char op)
{
for(int i=0; i<t.size(); i++)
if(t[i] == op)
return i;
return -1;
}
int LeftDigitPos(string s, int p)
{
int left;
for(int i=p; i>=0; i--){
if(s[i]>='0' && s[i]<='9') left = i;
else break;
}
return left;
}
int RightDigitPos(string s, int p)
{
int right;
for(int i=p; i<s.size(); i++){
if(s[i]>='0' && s[i]<='9') right = i;
else break;
}
return right;
}
int Plus(string s)
{
for(int index=findOp(s,'+'); index!=-1; index=findOp(s,'+'))
{
int left = LeftDigitPos(s, index-1);
string sa = s.substr(left,index-left);
int a = StoI(sa);
int right = RightDigitPos(s,index+1);
string sb = s.substr(index+1,right-index);
int b = StoI(sb);
int c = a + b;
string sc = ItoS(c);
s = s.substr(0,left) + sc + s.substr(right+1,s.size()-right-1);
}
return StoI(s);
}
int Plus_Mulity(string s)
{
for(int index=findOp(s,'*'); index!=-1; index=findOp(s,'*'))
{
int left = LeftDigitPos(s, index-1);
string sa = s.substr(left,index-left);
int a = StoI(sa);
int right = RightDigitPos(s,index+1);
string sb = s.substr(index+1,right-index);
int b = StoI(sb);
int c = a * b;
string sc = ItoS(c);
s = s.substr(0,left) + sc + s.substr(right+1,s.size()-right-1);
}
return Plus(s);
}
int kuohao(string s)
{
int left = findOp(s,'(');
int right = findOp(s,')');
if(left==-1 || right==-1) return Plus_Mulity(s);
string t = s.substr(left+1, right-left-1) ;
int c = Plus_Mulity(t);
string sc = ItoS(c);
s = s.substr(0,left) + sc + s.substr(right+1,s.size()-right-1);
return Plus_Mulity(s);
}
int main()
{
string s;
cin>>s;
int ans = kuohao(s);
cout<<ans;
return 0;
}
关于算数表达式4的正确代码
最新推荐文章于 2024-07-25 21:13:04 发布