1. 程式人生 > 資訊 >輕音自然風,創維空氣迴圈扇 29 元起季前衝量

輕音自然風,創維空氣迴圈扇 29 元起季前衝量

✔做題思路or感想:

  • 擺明了用棧來寫

    • 如果字串是正數,則把字串轉化為數字push進棧中

    • 如果字串是負數,則先忽略第一個負號並將其轉化為數字,最後再乘個-1,push進棧中

    • 如果字串是運算子,則取棧頂前兩個元素出來進行運算,然後把結果再push進棧中

      最後棧頂元素就是答案

      class Solution {
      public:
          int evalRPN(vector<string>& tokens) {
              stack<int> st;
              for (int i = 0; i < tokens.size(); i++) {
                  if (tokens[i][0] == '-' && tokens[i].size() > 1) {	//遇到負數的解決情況
                      int a = 0, size = tokens[i].size() - 1;
                      for (int j = 1; j < tokens[i].size(); j++) {
                          a = a * 10 + tokens[i][j] - '0';
                      }
                      st.push(-1 * a);
                  } else if (tokens[i] == "+") {
                      int a = st.top();
                      st.pop();
                      int b = st.top();
                      st.pop();
                      st.push(a + b);
                  } else if (tokens[i] == "-") {
                      int a = st.top();
                      st.pop();
                      int b = st.top();
                      st.pop();
                      st.push(b - a);
                  } else if (tokens[i] == "*") {
                      int a = st.top();
                      st.pop();
                      int b = st.top();
                      st.pop();
                      st.push(a * b);
                  } else if (tokens[i] == "/") {
                      int a = st.top();
                      st.pop();
                      int b = st.top();
                      st.pop();
                      st.push(b / a);
                  } else {
                      int a = 0;
                      for (int j = 0; j < tokens[i].size(); j++) {	//遇到正數的情況
                          a = a * 10 + tokens[i][j] - '0';
                      }
                      st.push(a);
                  }
              }
              return st.top();
          }
      };