Leetcode#150 Evaluate Reverse Polish Notation

原题地址

 

基本栈操作。

注意数字有可能是负的。

 

代码:

 1 int toInteger(string &s) {

 2   int res = 0;

 3   bool negative = s[0] == '-' ? true : false;

 4         

 5   for (int i = negative ? 1 : 0; i < s.length(); i++) {

 6     res *= 10;

 7     res += s[i] - '0';

 8   }

 9   return negative ? -res : res;

10 }

11     

12 int compute(int a, int b, string sign) {

13   switch (sign[0]) {

14   case '+':

15     return a + b;

16   case '-':

17     return a - b;

18   case '*':

19     return a * b;

20   case '/':

21     return a / b;

22   default:

23     return -1;

24   }

25 }

26     

27 int evalRPN(vector<string> &tokens) {

28   stack<int> st;

29         

30   for (auto t : tokens) {

31     if (t.length() > 1 || t[0] >= '0' && t[0] <= '9')

32       st.push(toInteger(t));

33     else {

34       int b = st.top();

35       st.pop();

36       int a = st.top();

37       st.pop();

38       st.push(compute(a, b, t));

39     }

40   }

41         

42   return st.top();

43 }

 

你可能感兴趣的:(LeetCode)