Basic Calculator II(**)

题目:
计算输入字符串的值 “3 + 4 2 / 3 ”

思路:
用栈来存值

public class Solution {
   public static int calculate(String s) {
        char[] chars = s.trim().toCharArray();
        LinkedList<Integer> numStack = new LinkedList<> ();
        LinkedList<Character> opratorQueue = new LinkedList<> ();

        int[] res = new int[1];
        for(int i = 0 ; i < chars.length ;) {
            char c = chars[i];
            i++;
            switch(c) {
            case ' ' : 
                continue;
            case '+' :  
                opratorQueue.add('+');
                break;
            case '-' :
                opratorQueue.add('-');
                break;
            case '*' :
                int pre = numStack.removeLast();
                i = getNext(chars , i , res);
                int next = res[0];
                numStack.add(pre * next);
                break;
            case '/' :
                int dpre = numStack.removeLast();
                i = getNext(chars , i , res);
                int dnext = res[0];
                numStack.add(dpre / dnext);
                break;
            default :
                i = getNext(chars , i-1 , res);
                numStack.add(res[0]);
            }
        }

        // System.out.println(numStack +" " +'\n' + opratorQueue);    
        while(!opratorQueue.isEmpty()) {
            int pre = numStack.removeFirst();
            int next = numStack.removeFirst();
            char opra = opratorQueue.removeFirst();
            if(opra == '+') numStack.addFirst(next + pre);
            else numStack.addFirst(pre - next);
        }
        return numStack.getFirst();
    }

    // 不能以单个字符 表示一个数组 ,42就是两个字符
    private static int getNext(char[] chars, int i , int[] res) {
        String s = "";
        for( ; i < chars.length ; i++) {
            if(chars[i] == ' ') continue;
            if(chars[i] == '+' || chars[i] == '-'
                    || chars[i] == '*' || chars[i] == '/') break;
            s += chars[i];
        }
        res[0] = Integer.parseInt(s);
        return i;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值