首页 > 其他 > 详细

Leetcode: Basic Calculator

时间:2015-12-19 06:36:18      阅读:245      评论:0      收藏:0      [点我收藏+]
Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Notice:

1. 检查数,比如2位数,3位数

2. 用stack,遇到 ‘(‘ 就把之前的结果和符号push进stack. 遇到‘)‘就把 当前结果*stack中的符号 再加上stack中之前的结果.

 1 public class Solution {
 2     public int calculate(String s) {
 3         if (s==null || s.length()==0) return 0;
 4         Stack<Integer> stack = new Stack<Integer>();
 5         int sign = 1;
 6         int num = 0;
 7         int sum = 0;
 8         for (int i=0; i<s.length(); i++) {
 9             char c = s.charAt(i);
10             if (c>=‘0‘ && c<=‘9‘) {
11                 if (i<s.length()-1 && s.charAt(i+1)>=‘0‘ && s.charAt(i+1)<=‘9‘) {
12                     num = num * 10 + (int)(c - ‘0‘);
13                     continue;
14                 }
15                 else num = num * 10 + (int)(c - ‘0‘);
16                 sum += sign * num;
17                 num = 0;
18             }
19             if (c == ‘+‘) sign = 1;
20             if (c == ‘-‘) sign = -1;
21             if (c == ‘(‘) {
22                 stack.push(sum);
23                 stack.push(sign);
24                 sign = 1;
25                 sum = 0;
26             }
27             if (c == ‘)‘) {
28                 sum = stack.pop()*sum + stack.pop();
29                 sign = 1;
30             }
31         }
32         return sum;
33     }
34 }

 

Leetcode: Basic Calculator

原文:http://www.cnblogs.com/EdwardLiu/p/5058595.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!