Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
basic caculate i
// Calculate I // The expression string may contain "(", ")", +, -, no-negative integers and empty spaces. // Input: "(1+(4+5+2)-3)+(6+8)" // Output: 23 #include <iostream> #include <stack> using namespace std; int calculate_1(string s) { stack<long> stack; long n = 0; long sgn = 1; long res = 0; for(int i=0; i<s.size(); i++){ char c = s[i]; if(isdigit(c)){ n = n*10 + c - '0'; } else if (c == '+' ){ res += n * sgn; n = 0; sgn = 1; } else if (c == '-' ){ res += n * sgn; n = 0; sgn = -1; } else if (c == '(' ){ // push stack.push(res); stack.push(sgn); res = 0; sgn = 1; } else if (c == ')' ){ // pop res += n*sgn; n = 0; sgn = stack.top(); stack.pop(); res = res *sgn ; // NOTE!! res += stack.top(); stack.pop(); } } if(n !=0) res += n*sgn; return res; } int main(){ string s = "(1+(4+5+2)-3)+(6+8)"; cout << s << " = " << calculate_1(s) << endl; }
run
|
edit
|
history
|
help
0
VirtualResto
synowie abrahama
reverse function
hilbert
Exempel 2
alma
ListCPP
C++ Inheritance Example
chocolate Distribution Problem
Make BinTree