题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            int x=solve(a);
            System.out.print(x);
        }
    }
    public static int solve(String str){
        Stack<Integer> stack = new Stack<>();
        int n=str.length();
        int num=0;
        char sign='+';
        for(int i=0;i<n;i++){
            char cha=str.charAt(i);
            if(Character.isDigit(cha)){
                num=num*10+(cha-'0');
			  //这里切记 千万不要看到数字就手贱continue了,如果是最后一个字符会在本循环处理的
			  //这个BUG我找了半小时
            }
            if(cha=='('){
                int count=1;
                int j=i+1;
                while(count!=0){
                    if(str.charAt(j)=='(') count++;
                    if(str.charAt(j)==')') count--;
                    j++;
                }
                String str_=str.substring(i+1,j-1);
                num=solve(str_);
                i=j-1;
            }
            if(!Character.isDigit(cha)||i==n-1){
                if(sign=='+'){
                    stack.add(num);
                    num=0;
                }
                if(sign=='-'){
                    stack.add(-1*num);
                    num=0;
                }
                if(sign=='*'){
                    stack.add(stack.pop()*num);
                    num=0;
                }
                if(sign=='/'){
                    stack.add(stack.pop()/num);
                    num=0;
                }
                sign=cha;
            }
        }
        int val=0;
        while(!stack.isEmpty()){
            val+=stack.pop();
        }
        return val;
    }
}

全部评论

相关推荐

01-11 08:47
门头沟学院 Java
choumoduji...:读研的目的就是为了以最快的速度和最低的要求完成“学校”规定的毕业标准,而不是所谓课题组的要求
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务