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();
    
            
           
        }
    }
    

      

  • 相关阅读:
    android 启动报错
    android 百度地图
    android LayoutInflater使用
    spring mvc No mapping found for HTTP request with URI [/web/test.do] in DispatcherServlet with name 'spring'
    sql mysql和sqlserver存在就更新,不存在就插入的写法(转)
    jsp include
    json 解析
    css
    Scrapy组件之item
    Scrapy库安装和项目创建
  • 原文地址:https://www.cnblogs.com/CongLollipop/p/6771125.html
Copyright © 2011-2022 走看看