Take the vector as a stack and then keep reading and pop. First the product or quotient is good and then deposited in the stack
PS. For a long time did not refer to other direct self-written AC code ... Various bugs ... Sure enough to practice well ...
1. Consider the space situation; 2. Consider the digital situation; 3. Consider the boundary of index
Class Solution {
Public
int calculate (string s) {
int Len=s.length ();
Vector<char> Stack;
int first = 0;
int second=0;
int Temp;int bit=0;
int flag;
for (int i=0;i<len;i++)
{
if (s[i]<= ' 9 ' &&s[i]>= ' 0 ')
Stack.push_back (S[i]);
else if (s[i]== '-' | | | s[i]== ' + ')
Stack.push_back (S[i]);
else if (s[i]== '/' | | | s[i]== ' * ')
{
First=0;second=0;bit=0;flag=i;
while (Stack.back () <= ' 9 ' &&stack.back () >= ' 0 ')
{
first=first+ (Stack.back ()-' 0 ') *pow (10,bit++);
Stack.pop_back ();
}
i++;bit=0;
while ((s[i]<= ' 9 ' &&s[i]>= ' 0 ') | | s[i]== ")
{
if (s[i]== ")
{
i++;
if (I==len) break;
else continue;
}
second=second*10+ (s[i]-' 0 ');
i++;
if (I==len) break;
else if (s[i]< ' 0 ' | | S[i]> ' 9 ')
{
I--;break;
}
}
if (s[flag]== '/')
Temp=first/second;
else if (s[flag]== ' * ')
Temp=first*second;
if (temp==0)
{
Stack.push_back (' 0 ');
Continue
}
vector<char>tmp;
while (temp>0)
{
Tmp.push_back ((temp%10) + ' 0 ');
TEMP=TEMP/10;
}
while (!tmp.empty ())
{
Stack.push_back (Tmp.back ());
Tmp.pop_back ();
}
if (I==len) break;
}
}
int result=0;bit=0;
First=0;second=0;
while (!stack.empty ())
{
if (Stack.back () <= ' 9 ' &&stack.back () >= ' 0 ')
{
first+= (Stack.back ()-' 0 ') *pow (10,bit++);
Stack.pop_back ();
}
Else
{
bit=0;
if (stack.back () = = ' + ')
Result+=first;
Else
Result-=first;
Stack.pop_back ();
first=0;
}
}
Result+=first;
return result;
}
};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Basic Calculator II