标签:code operator eve org i++ eval express -- leetcode
1 class Solution { 2 public: 3 int strtoint(string s) // string转int 4 { 5 int result = 0; 6 int base = 1;//记录属于的位 7 int t = 1;//记录正负号 8 if(s[0] == ‘-‘) 9 t = -1; 10 for(int i= s.size() - 1;i>=0;i--) 11 { 12 if(s[i]>=‘0‘ && s[i]<=‘9‘)//此处一定注意0和9加‘‘ 13 { 14 result += base * (s[i] - ‘0‘); 15 base *= 10; 16 } 17 } 18 return result*t; 19 } 20 int evalRPN(vector<string> &tokens) { 21 int n = tokens.size(); 22 if(tokens.empty() || n<=0) 23 return 0; 24 stack<int> s; 25 for(int i=0;i<n;i++) 26 { 27 if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") 28 { 29 int num2 = s.top();//先弹出的为右操作数 30 s.pop(); 31 int num1 = s.top(); 32 s.pop(); 33 if(tokens[i] == "+") 34 { 35 s.push(num1+num2); 36 } 37 else if(tokens[i] == "-") 38 { 39 s.push(num1-num2); 40 } 41 else if(tokens[i] == "*") 42 { 43 s.push(num1*num2); 44 } 45 else 46 { 47 s.push(num1/num2); 48 } 49 } 50 else 51 { 52 s.push(strtoint(tokens[i])); 53 } 54 } 55 return s.top(); 56 } 57 };
leetcode栈--1、evaluate-reverse-polish-notation(逆波兰表达式)
标签:code operator eve org i++ eval express -- leetcode
原文地址:http://www.cnblogs.com/qqky/p/6939761.html