Run Code
|
API
|
Code Wall
|
Users
|
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
Please
log in
to post a comment.
Matrix multiplication naive approach
Buenos Amigos
RandomMessage
Listas enlazadas - k-esimo elemento
isBST
TwoVarRegression
std_minmax_unexpected_behaviour.cpp
numberOftweets
Web Browser History
BFS Basic
Please log in to post a comment.