The title and the previous "
Basic Calculator "is the same way of handling, just adding support for both" * "and"/"operations.
Class Solution {Public:bool isnum (char c) {if (c >= ' 0 ' && C <= ' 9 ') return true; return false; } int Calculate (string s) {vector<string> postorder; Stack<char> CCache; Stack<int> Icache; string tmp; if (S.length () < 1) return 0;//constructs a suffix expression for (int i = 0; i < s.length ();) {if (s[i] = = ") {i++; Continue } if (!isnum (S[i])) {if (s[i] = = ' (' | | ccache.empty ()) {Ccache.push (s[i]); i++; Continue } if (s[i] = = ') ') {while (Ccache.top ()! = ' (') {tmp = ""; TMP + = Ccache.top (); Postorder.push_back (TMP); Ccache.pop (); } ccache.pop (); i++; Continue } if (s[i] = = ' + ' | | s[i] = = '-') {while (!ccache.empty () && ccache.top ()! = ' (') {tmp = ""; TMP + = Ccache.top (); Postorder.push_back (TMP); Ccache.pop (); } ccache.push (S[i]); i++; Continue } if (s[i] = = ' * ' | | s[i] = = '/') {while (!ccache.empty () && ccache.top ()! = ' (' & amp;& ccache.top ()! = ' + ' && ccache.top ()! = '-') {tmp = ""; TMP + = Ccache.top (); Postorder.push_back (TMP); Ccache.pop (); } ccache.push (S[i]); i++; Continue }}else{Int j = i; while (j < S.length () && isnum (S[j]) j + +; TMP = ""; TMP = S.SUBSTR (i, j-i); Postorder.push_back (TMP); i = j; }//Add all remaining elements while (!ccache.empty ()) {tmp = ""; TMP + = Ccache.top (); Ccache.pop (); Postorder.push_back (TMP); }
Evaluates the result value with a suffix expression int fir, sec, result; for (int i = 0; i < postorder.size (); i++) { if (postorder[i] = = "+" | | postorder[i] = "-" | | postorder[i] = = "*" | | Postorder[i] = = "/") { sec = Icache.top (); Icache.pop (); FIR = Icache.top (); Icache.pop (); if (postorder[i] = = "+") result = Fir + sec; if (postorder[i] = = "-") result = Fir-sec; if (postorder[i] = = "*") result = Fir * sec; if (postorder[i] = = "/") result = Fir/sec; Icache.push (result); } else{ Icache.push (atoi (Postorder[i].c_str ())); } } return Icache.top (); }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Basic Calculator II