LeetCode.224 基本计算器

原题

https://leetcode-cn.com/problems/basic-calculator/

在这里插入图片描述

思路

  • 从左到右进行遍历,计算
  • 如果没有(,则一直进行简单计算
  • 如果遇到(,则将(前边的结果入栈,(前边的符号入栈
  • 如果遇到),则将符号和前边的结果都出栈

4个变量,resnumsign

题解

package com.leetcode.code;

import java.util.Stack;

/**
 * @ClassName Code224
 * @Author ZK
 * @Description
 * @Date 2021/3/10 10:09
 * @Version 1.0
 **/
public class Code224 {

    public static void main(String[] args) {
        String s = "2147483647";
//        String s = "123";
        System.out.println(calculate(s));
    }

    public static int calculate(String s) {
//        计算结果,部分计算结果,括号中计算结果
        int res = 0;
//        当前的数字,例如:1+23中的1或者23
        int num = 0;
//        符号,加号(+1)或者减号(-1)
        int sign = 1;
//        当右括号时,用于存储计算结果
        Stack<Integer> stack = new Stack<>();

        char[] chars = s.toCharArray();
        int len = chars.length;

        for (int i = 0; i < len; i++) {
            char c = chars[i];
//            如果当前字符为' ',则直接continue
            if (c == ' ') {
                continue;
            }
//            如果当前字符是一个数字,则用num进行记录
//            当前有可能是一个>9的数字,所以需要num = num * 10 + c - '0'
            if (c >= '0' && c <= '9') {
                num = num * 10 + c - '0';
//                判断当前数字是否已经取完
//                例如:123+4,只有当取到+时,才能确定123为当前的num
                if (i < len-1 && '0' <= chars[i+1] && chars[i+1] <= '9') {
                    continue;
                }
//            如果当前字符为'+'或者'-'
            } else if (c == '+' || c == '-') {
//                将num置为0,用来存放当前符号(+/-)之后的数字
                num = 0;
//                如果当前符号为+,则sign为+1
//                如果当前符号为-,则sign为-1
                sign = c=='+' ? 1 : -1;
//            如果当前符号为'('
            } else if (c == '(') {
//                例如当前表达式为:'123+(...)'
//                则将res:123,入栈
                stack.push(res);
//                则将sign:+,入栈
                stack.push(sign);
//                同时res置为0,用来保存()中的计算结果
                res = 0;
//                sign置为初始状态,为1
                sign = 1;
//            如果当前符号为')'
            } else if (c == ')') {
//                '('前边的符号出栈
                sign = stack.pop();
//                将num替换为括号中的计算结果
                num = res;
//                将res替换为括号前边的计算结果
                res = stack.pop();
            }
//            每遍历一次,得到一个res
            res += sign * num;
        }
        return res;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值