牛客网真题-55-表达式计算

简单表达式计算

http://www.nowcoder.com/questionTerminal/6221faa383fc49f1b10dffcb62c866bf

if-else疯狂判断

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;


public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = bufferedReader.readLine()) != null) {
            if(s.equals("END")){
                break;
            }
            Stack<Integer> ints = new Stack<>();

            Stack<Character> chars = new Stack<>();
            String num = "";
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) < '0' || s.charAt(i) > '9'){
                    ints.add(Integer.parseInt(num));
                    num = "";
                    chars.add(s.charAt(i));
                }else{
                    num += s.charAt(i);
                }
            }
            ints.add(Integer.parseInt(num));
            Long cnt = 0L, temp = 1L;
            while (!chars.isEmpty()) {
                char c = chars.pop();
                if(c == '+'){
                    if(temp == 1L){
                        cnt += ints.pop();
                    }else{
                        cnt += temp * ints.pop();
                    }
                    temp = 1L;
                }else if(c == '-'){
                    if(temp == 1L){
                        cnt -= ints.pop();
                    }else{
                        cnt -= temp * ints.pop();
                    }
                    temp = 1L;
                }else if(c == '*'){
                    temp *= ints.pop();
                }
            }
            cnt += temp * ints.pop();
            System.out.println(cnt);

        }
    }
}
全部评论

相关推荐

05-03 12:45
西南大学 Java
nsnzkv:你这项目写的内容太多了,说实话都是在给自己挖坑,就算简历过了,后面面试也难受
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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