1. 程式人生 > 其它 >leetcode(c++)計算器類

leetcode(c++)計算器類

#include <iostream>
#include <string>
#include <stack>

using namespace  std;

int calculator0(string s)
{
    stack<int>st;
    char opt = '+';
    int num = 0;
    for(int i = 0; i < s.size(); ++i)
    {
        char c = s[i];
        if(c>='0' && c <= '9')
        {
            num 
= num * 10 + (c - '0'); } if(i == s.size() - 1 || c == '+' || c == '-') { if(opt == '+') { st.push(num); } else { st.push(-num); } opt = c; num = 0; } }
int ans = 0; while(!st.empty()) { ans += st.top(); st.pop(); } return ans; } int calculator1(string s) { char opt = '+'; stack<int>st; int num = 0; for(int i = 0; i < s.size(); ++i) { char c = s[i]; if(c >= '0' && c <= '
9') { num = num * 10 + (c - '0'); } if(i == s.size() - 1 || c == '+' || c == '-' || c == '*' || c== '/') { if(opt == '+') { st.push(num); } else if(opt == '-') { st.push(-num); } else if(opt == '*') { int tmp = st.top() * num; st.pop(); st.push(tmp); } else { float tmp = st.top() / num; st.pop(); st.push(tmp); } opt = c; num = 0; } } int res = 0; while(!st.empty()) { res += st.top(); st.pop(); } return res; } int i = 0; int calculator2(string s) { int num = 0; stack<int>st; char opt = '+'; while(i < s.size()) { char c = s[i++]; if(c >= '0' && c <= '9') { num = num * 10 + (c - '0'); } if(c == '(')num = calculator2(s); if(i >= s.size() || c == '+' || c == '-' || c == '*' || c == '/' || c == ')') { if(opt == '+') { st.push(num); } else if(opt == '-') { st.push(-num); } else if(opt == '*') { int tmp = st.top() * num; st.pop(); st.push(tmp); } else if(opt == '/') { int tmp = st.top() / num; st.pop(); st.push(tmp); } opt = c; num = 0; } if(c == ')')break; } int ans = 0 ; while(!st.empty()) { // cout << st.top() << endl; ans += st.top(); st.pop(); } return ans; } int main() { // //實現簡單的只有+ - 的計算器 // cout << calculator0("-2") << endl; // //實現包含+ - * /的計算器 // cout << calculator1("9+2/3") << endl; //實現包含帶()的計算器 cout << calculator2("(1 + (4 + 5 +2) - 3)+(6+8)") << endl; cout << calculator2("(2 + 6 * 3 + 5- (3*14/7+2)*5)+3") << endl; cout << calculator2("1 + 1") << endl; return 0; }