Basic Calculator
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open(
and closing parentheses)
, the Plus+
or minus sign-
,non-negativeIntegers and empty spaces
.
Assume that the given expression was always valid.
Some Examples:
"1 + 1" = 2 "2-1 + 2" = 3 "(1+ (4+5+2)-3) + (6+8)" = 23
Note: don't use the eval
built-in library function.
Problem Solving Ideas:
Simple calculator. The infix expression is now converted to a suffix expression, which is then calculated using the stack. There are a few points to note. 1. Conversion of suffix expression. 2, for the minus, note which number is the meiosis, which is the meiosis. This program can easily be modified to include subtraction's calculator problem. The difference is that the conversion of the suffix expression is not the same.
Class Solution {Public:int calculate (string s) {string PostS = getpoststring (s); get postfix expression cout << posts;stack<int> nums;int len = posts.length (); int num1, num2;for (int i = 0; i<len; i++) { Switch (Posts[i]) {case ' + ': NUM1 = Nums.top (); Nums.pop (); num2 = Nums.top (); Nums.pop (); num1 = Num1 + Num2;nums.push (NUM1); Break;case '-': Num1 = Nums.top (); Nums.pop (); num2 = Nums.top (); Nums.pop (); num1 = num2-num1;//note Here is num2 minus Num1nums.push ( NUM1); Break;case ' # ': Break;default:int num = 0;while (i < len && posts[i] >= ' 0 ' && posts[i] <= ' 9 ') {num = num * + (posts[i]-' 0 '); i++;} I--;nums.push (num); break;}} return Nums.top ();} Private:string getpoststring (String s) {string PostS = "";stack<char> op;int len = s.length (); for (int i = 0; i<len; i++) {switch (S[i]) {case ": Break;case ' (': Op.push ('); Break;case ') ': while (!op.empty () && op.top ()! = ' (') { PostS + = Op.top (); Op.pop ();} if (!op.empty () && op.top () = = ' (') {Op.pop ();} Break;case ' + ': case '-': while (!op.empty () && op.top ()! = ' (') {PostS + = Op.top (); Op.pop ();} Op.push (S[i]) break;default:while (I<len && s[i] >= ' 0 ' &&s[i] <= ' 9 ') {PostS + = s[i];i++;} PostS + = ' # '; Separate digital I--;break;}} while (!op.empty ()) {PostS + = Op.top (); Op.pop ();} return PostS;};
[Leetcode] Basic Calculator