[编程题]evaluate-reverse-polish-notati


Q:Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

Some examples:  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6



A:
 1 class Solution {
 2 public:
 3     int evalRPN(vector<string> &tokens) {
 4         stack<int> numbers;
 5         for(auto token : tokens)
 6         {
 7             if(token == "+" || token == "-" || token == "*"||token == "/")
 8             {
 9                 int a,b,res;
10                 b=numbers.top();numbers.pop();
11                 a=numbers.top();numbers.pop();
12                 if(token == "+")
13                     res=a+b;
14                 else if(token == "-")
15                     res=a-b;
16                 else if(token == "*")
17                     res=a*b;
18                 else
19                     res=a/b;
20                 numbers.push(res);
21             }
22             else 
23             {
24                 stringstream ss;
25                 ss<<token;
26                 int temp;
27                 ss>>temp;
28                 numbers.push(temp);
29             }
30         }
31         return numbers.top();     
32     }
33 }
 
涉及知识点

1.stack 的使用

//----------------------------------------- 读取堆栈的栈顶元素
#include <stack>
#include <iostream>
using namespace std;
int main()
{
    // 创建堆栈对象
    stack<int> s;
    // 元素入栈
    s.push(3);
    s.push(19);
    s.push(23);
    s.push(36);
    s.push(50);
    s.push(4);

    // 元素依次出栈
    while(!s.empty())
    {
        // 打印栈顶元素,打印出:4 50 36 23 19 3
        cout << s.top() << endl;
        // 出栈
        s.pop();
    }

    return 0;
}

2. stringstream的用法

可以作为将数字和字符串相互转化的工具。

std::string name("12345");
    int age = 27;
    stringstream os;
    os << name;
    os >> age;
    // age = 12345
    cout<<age<<endl;

std::string name("12345");
int age = 27;
stringstream os;
os << age;
os >> name;
// name:27
cout<<name<<endl;

 

猜你喜欢

转载自www.cnblogs.com/xjyxp/p/11136953.html