Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
basic caculate iii
// Calculate III // The expression string may contain (, ) +, -, *, /, and empty spaces. // Input: "2*(1+2*5-2/2)+1" = 21 #include <iostream> #include <stack> #include <vector> using namespace std; long eNum(string& s, int& i) { long n = 0; while(i < s.length() && isdigit(s[i])) n = s[i++] - '0' + 10 * n; return n; } long experssion(string& s, int& i) { vector<long> nums; // you can use either vector or stack char op = '+'; for (; i < s.length() && op != ')'; i++) { // op can take value of +, -, *, / & ) if (s[i] == ' ') continue; // skip for space long n = s[i] == '(' ? experssion(s, ++i) : eNum(s, i); switch(op) { case '+' : nums.push_back(n); break; case '-' : nums.push_back(-n); break; case '*' : nums.back() *= n; break; case '/' : nums.back() /= n; break; } op = s[i]; } long res = 0; // return results for (int n : nums) res += n; return res; } int calculate(string s) { int i = 0; return experssion(s, i); } int main(){ string s = "2*(5+5*2)/3+(6/2+8)"; // = 21 cout << s << " = " << calculate(s) << endl; }
run
|
edit
|
history
|
help
0
shuffle_example
ConvHull
Network UVa
Eratosfen conmment
Power of an element
Lazy String Tokenizer Class
Zadanie Kalkulator z bajerami
qwerty
Metodos
sd