Java implementation of the Blue Bridge Cup VIP training algorithm binary function

Examination training algorithm binary function

Resource limitation
time limit: 1.0s memory limit: 256.0MB
description of the problem
  to make binary function f (x, y) = ax + by, a and b are integers, evaluating an expression of the S.
  Only the following expression is legal requirements:
  1. arbitrary integer x is a valid expression;
  2. If A and B are legal expression, F (A, B) is a valid expression .
Input format
  of the first number of a row and two B;
  second line S represents a string expression required.
Output format
  line number represents a value of the expression of S.
Sample input
. 1 2
F (. 1, F (. 1, -1))
sample outputs
-1
size of the data and the agreed
  length S no more than 50, the process operation for all of the variables are not exceeded int.

package 第十次模拟;

import java.util.Scanner;
import java.util.Stack;

public class 二元函数 {
	 public static void main(String[] args) {
		   Stack<Integer> num = new Stack<Integer>();
		  Scanner sc = new Scanner(System.in); 	
		   int a  = sc.nextInt(); 
		   int b = sc.nextInt();
		   sc.nextLine(); //用于消除第一个回车
		   String str = sc.nextLine();  //输入字符串
		   try {
			   if(Integer.valueOf(str)>0){
				   System.out.println(str);
				   return;
			   }
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		    char[] s = str.toCharArray();	 //转换为数组操作
		   	 for(int i =0 ;i < s.length;i++){
		   		 if(s[i] == '-'){ 	  //如果是  为负数
		   			 i++ ;    //使索引指向负号下面一个元素
		   			 i = 	getNumber(num, s, i,false);
		   		 }else if(Character.isDigit(s[i])){ //
		   			 i = 	getNumber(num, s, i,true);
		   		  	}
		   		 if(s[i] == ')'){
		   			 int x = num.pop();
		   			 int y = num.pop();
		   			 //x应该是在算式中是靠后的元素,所以应该互换位置
		   			num.push(count(a,b,y,x)) ;
		   		 }
		   	 }
		   	 System.out.println(num.pop());
	}
	   //计算一个f()的值 。
	   public static int count(int a , int b , int x , int y){
		   return a*x+b*y;
	   }
	   //获取一个完整的数值。  返回一个索引
	   public static int  getNumber(Stack<Integer> stack,char[] s  ,int i,Boolean pos){
		   int number = 0 ;
		   for(;s[i] != ','&&s[i]!=')';i++){
			 		 number = number * 10 +s[i]-'0';
			 	 }
		   if(!pos){
			   stack.push(-number);  //对有符号的进行取反处理
		   } else 
			   //入栈操作
		   stack.push(number);
		   if(s[i] == ' '){
			   return i ;
		   }
		   return i ;
	   }


}

Released 1411 original articles · won praise 10000 + · views 1.48 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104669094