Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
basic caculate ii
// Calculate II // The expression string may contain +, -, *, /, and empty spaces. // Input: "3+5 / 2 " = 5 #include <iostream> #include <stack> using namespace std; int calculate2(string s) { long res = 0; long n = 0; char sgn = '+'; stack<long> stack; for(int i=0; i<s.size(); i++){ char c = s[i]; if(isdigit(c)) n = n*10+ c - '0'; if(!isdigit(c) && c !=' ' || i == s.size()-1 ){// ops or last element switch(sgn){ case '*': stack.top() *= n; break; case '/': stack.top() /= n; break; case '+': stack.push(n); break; case '-': stack.push(-n); break; } n = 0; sgn = c; // } } while(stack.size()){ res += stack.top(); stack.pop(); } return res; } int main(){ string s = "3+5 / 2 "; cout << s << " = " << calculate2(s) << endl; }
run
|
edit
|
history
|
help
0
find first non repeating
Polyrmophism
Minimum Vertices to Traverse Directed Graph
MyStack
barai_1
Guess Number
big boom!
Test 15(2020)
Undefined behaviour
5345