• Java实现 蓝桥杯 算法训练 前缀表达式


    算法训练 前缀表达式
    时间限制:1.0s 内存限制:512.0MB
    问题描述
      编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
      输入格式:输入只有一行,即一个前缀表达式字符串。
      输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
      输入输出样例
    样例输入

    • 5 2
      样例输出
      7
    import java.util.Scanner;
    
    
    public class 前缀表达式 {
    	public static void main(String[] args) {
    		Scanner input=new Scanner(System.in);
    		String str=input.nextLine();
    		input.close();
    		int result = 0;
    		int num1=Integer.parseInt(str.charAt(2)+"");
    		if(Character.isDigit(str.charAt(3)))
    			num1=num1*10+Integer.parseInt(str.charAt(3)+"");
    		int num2=Integer.parseInt(str.charAt(str.length()-1)+"");    //最后一个数字(如果最后一个数字为两位,则这是个位)
    		if(Character.isDigit(str.charAt(str.length()-2)))     //如果倒数第二位也是数字,则需要加上
    			num2=Integer.parseInt(str.charAt(str.length()-2)+"")*10+num2;
    		switch (str.charAt(0)) {
    		case '+':
    			result=num1+num2;
    			break;
    		case '-':
    			result=num1-num2;
    			break;
    		case '*':
    			result=num1*num2;
    			break;
    		case '/':
    			result=num1/num2;
    			break;
    		}
    		System.out.println(result);
    	}
    
    
    }
    
    
  • 相关阅读:
    70个经典的 Shell 脚本面试问题
    shell 知识点
    awk
    chinaunix-索引资料
    一篇文章学会shell工具篇之sed
    linux shell 之if-------用if做判断
    Python shell对比
    TortoiseGit功能介绍
    gitlab图形化使用教程 (mtm推荐)
    gitlab 服务器的搭建与使用全过程(一)
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12948741.html
Copyright © 2020-2023  润新知