Java实现蓝桥杯VIP算法训练 二元函数

试题 算法训练 二元函数

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  令二元函数f(x,y)=ax+by,a和b为整数,求一个表达式S的值。
  只有满足以下要求的表达式才是合法的:
  1.任意整数x是一个合法的表达式;
  2.如果A和B都是合法的表达式,则f(A,B)也是一个合法的表达式。
输入格式
  第一行两个数a和b;
  第二行一个字符串S表示要求的表达式。
输出格式
  一行一个数表示表达式S的值。
样例输入
1 2
f(1,f(1,-1))
样例输出
-1
数据规模和约定
  S的长度不超过50,运算过程中所有变量不会超出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 ;
	   }


}

原文地址:https://www.cnblogs.com/a1439775520/p/13075924.html