# 0224. Basic Calculator ###### tags: `Leetcode` `Calculator` `Hard` Link: https://leetcode.com/problems/basic-calculator/ ## 思路 和其他calculator一样的写法~ ## Code ```java= class Solution { public int calculate(String s) { s = s.replaceAll(" ",""); char[] cs = s.toCharArray(); int len = s.length(); Stack<Integer> nums = new Stack<>(); nums.add(0); Stack<Character> ops = new Stack<>(); for(int i = 0;i < len;i++){ char c = cs[i]; if(c == '('){ ops.add('('); } else if(c == ')'){ while(!ops.isEmpty()){ if(ops.peek()!='('){ compute(nums, ops); } else{ ops.pop(); break; } } } else if(Character.isDigit(c)){ int num = 0; int j = i; while(j<len && Character.isDigit(cs[j])){ num = num*10 + (cs[j]-'0'); j++; } nums.add(num); i = j-1; } else{ if(i!=0 && (cs[i-1]=='('||cs[i-1]=='+'||cs[i-1]=='-')){ nums.add(0); } else{ while(!ops.isEmpty() && ops.peek()!='('){ compute(nums, ops); } } ops.add(c); } } while(!ops.isEmpty()) compute(nums, ops); return nums.peek(); } public void compute(Stack<Integer> nums, Stack<Character> ops){ int b = nums.pop(); int a = nums.pop(); char c = ops.pop(); if(c=='+') nums.push(a+b); if(c=='-') nums.push(a-b); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up