Skip to content

Latest commit

 

History

History
53 lines (52 loc) · 1.74 KB

227.md

File metadata and controls

53 lines (52 loc) · 1.74 KB

#227. Basic Calculator II 题目链接

建立两个int变量,一个用来存结果,另一个用来存储中间数据,中间数据的概念是只由乘或除计算出来的数据,一旦遇到加减,就把中间数据加入到结果当中。最后返回结果

public class Solution {
    public int calculate(String s) {
        int i = 0;
        StringBuilder sb = new StringBuilder();
        while (i < s.length() && (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == ' ')) {
            if (s.charAt(i) == ' ') {
                i++;
                continue;
            }
            sb.append(s.charAt(i));
            i++;
        }
        int result = 0;
        int temp = Integer.valueOf(sb.toString());
        while (i < s.length()) {
            char op = s.charAt(i++);
            StringBuilder num = new StringBuilder();
            while (i < s.length() && (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == ' ')) {
                if (s.charAt(i) == ' ') {
                    i++;
                    continue;
                }
                num.append(s.charAt(i));
                i++;
            }
            int nextnum = Integer.valueOf(num.toString());
            if (op == '+' || op == '-') {
                result += temp;
                if (op == '+') {
                    temp = nextnum;
                }
                else {
                    temp = -nextnum;
                }
            }
            else {
                if (op == '*') {
                    temp *= nextnum;
                }
                else {
                    temp /= nextnum;
                }
            }
        }
        return result + temp;
    }
}