[LeetCode] Basic Calculator II

Source: Internet
Author: User
Tags integer division

[LeetCode] Basic Calculator II
Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +,-, *, and/operators. The integer division shoshould truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7" 3/2 " = 1" 3+5 / 2 " = 5

Note: Do not useevalBuilt-in library function.

Credits:
Special thanks to @ ts for adding this problem and creating all test cases.

Solution:

Like Basic Calculator I, you only need to change the code to be converted into a suffix expression.

Class Solution {public: int calculate (string s) {string postS = getPostString (s); // obtain the suffix expression cout <postS; stack
 
  
Nums; int len = postS. length (); int num1, num2; for (int I = 0; I
  
   
= '0' & postS [I] <= '9') {num = num * 10 + (postS [I]-'0'); I ++ ;} I --; nums. push (num); break;} return nums. top ();} private: string getPostString (string s) {string postS = ""; stack
   
    
Op; int len = s. length (); for (int I = 0; I
    
     
= '0' & s [I] <= '9') {postS + = s [I]; I ++;} postS + = '#'; // separate the numbers I --; break;} while (! Op. empty () {postS + = op. top (); op. pop ();} return postS ;}};
    
   
  
 

Related Article

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.