Basic Calculator II LeetCode solution in C++
1class Solution {2public:3int calculate(string s) {4stack<int> nums;5stack<char> ops;6int n = 0;7for (int i = 0; i < s.size(); ++i) {8if (s[i] >= '0' && s[i] <= '9') {9string t(1, s[i]);10n = n * 10 + stoi(t);11} else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {12nums.push(n);13n = 0;14if (!ops.empty() && (ops.top() == '*' || ops.top() == '/')) {15int n2 = nums.top();16nums.pop();17int n1 = nums.top();18nums.pop();19if (ops.top() == '*')20nums.push(n1 * n2);21else22nums.push(n1 / n2);23ops.pop();24}25ops.push(s[i]);26}27}28nums.push(n);29if (!ops.empty() && (ops.top() == '*' || ops.top() == '/')) {30int n2 = nums.top();31nums.pop();32int n1 = nums.top();33nums.pop();34if (ops.top() == '*')35nums.push(n1 * n2);36else37nums.push(n1 / n2);38ops.pop();39}40stack<int> tnums;41stack<char> tops;42while (!nums.empty()) {43tnums.push(nums.top());44nums.pop();45}46while (!ops.empty()) {47tops.push(ops.top());48ops.pop();49}5051while (!tops.empty()) { // cout<<tops.top()<<" " ;52int n1 = tnums.top();53tnums.pop();54int n2 = tnums.top();55tnums.pop();56if (tops.top() == '+')57tnums.push(n1 + n2);58else59tnums.push(n1 - n2);60tops.pop();61}62return tnums.top();63}64};