[Leetcode] Basic Calculator II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.