zoukankan      html  css  js  c++  java
  • 逆波兰数Java实现

    定义^ 自增

    * 乘法

    + 加法

    栈长度16 超过 上溢出 返回-2  若栈中没有足够的整数供运算 则返回-1 否则返回栈顶

    package ali0426;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.Stack;
    
    public class Main {
    
        public static void main(String[] args) {
    
            ArrayList<Integer> inputs = new ArrayList<Integer>();
            Scanner in = new Scanner(System.in);
            String line = in.nextLine();
            if(line != null && !line.isEmpty()) {
                int res = resolve(line.trim());
                System.out.println(String.valueOf(res));
            }
        }
    
        // write your code here
        public static int resolve(String expr) {
        	String str [] = expr.split(" ");
        	
        	
        	Stack<Integer> sta = new Stack<>();
        	int temp1,temp2;
        	//char [] ch = expr.toCharArray();
        	for(int i=0;i<str.length;i++){
        		String  c = str[i];
        		if(sta.size()>16) return -2;  //上溢出
        		if(c.equals("^")){
        			if(sta.size()==0) return -1;
        			else{
        				temp1 = sta.pop();
        				temp1++;
        				sta.push(temp1);
        			}
        				
        			
        		}
        		else if(c.equals("+")){
        			if(sta.size()<2) return -1;
        			else{
        				temp1 =sta.pop();
        				temp2 = sta.pop();
        				sta.push(temp1+temp2);
        			}
        			
        		}
        		else if(c.equals("*")){
        			if(sta.size()<2) return -1;
        			else{
        				temp1 =sta.pop();
        				temp2 =sta.pop();
        				sta.push(temp1*temp2);
        		        
        			}
        			
        		}
        		else if(c.equals(" ")) continue;//处理空格
        		else{
        			sta.add(Integer.parseInt(c));
        		}
        		
        	}
    		return sta.peek();
    
            
           
        }
    }
    

      

  • 相关阅读:
    Metadata Lock原理5
    Seconds_Behind_Master
    Metadata Lock原理4
    MySQL Troubleshoting:Waiting on query cache mutex 腾讯数据库工程师:幕南风
    Metadata Lock原理2
    Metadata Lock原理1
    Online DDL与pt-online-schema-change
    Solaris 安装JDK
    RAID 概述
    4K Block Size的Device和 Aligned IO
  • 原文地址:https://www.cnblogs.com/CongLollipop/p/6771125.html
Copyright © 2011-2022 走看看