Training algorithm binary function

Here Insert Picture Description

import java.util.* ;
public class Main {
//定义两个输入的整数a和b,切记a,b不能放到main函数里面
public static int a ;
public static int b ;
public  static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
//输入两个整数a,b和字符串表达式
a = input.nextInt();
b = input.nextInt();
boolean flag = true ; //标记正负的,初始默认为正
String str = input.next() ;
char [] arr = str.toCharArray() ; //字符串表达式转换成字符数组
Stack <Integer> stack = new Stack<Integer>() ; //创建栈并实例化

for(int i=0; i<arr.length; i++) {
if(arr[i] == '-') { //负号,将flag标记为false
	flag = false ;
}
if(Character.isDigit(arr[i])) { //判断是否是数字
	int number = 0 ;
	for(; i <arr.length && Character.isDigit(arr[i]); i++) {
		//将字符数组转换成字符串类型再转换成整型,如果是连续的数字求出数的大小
		number = number * 10 + Integer.parseInt(String.valueOf(arr[i])) ;
	}
    i -- ; //最后的i会多加了个1,此处应该减去
	if(flag) { //如果是正整数,则直接进栈
		stack.push(number) ;	
		}
	if(!flag) { //如果是负整数,乘-1后进栈,
		stack.push(number * (-1)) ;
		flag = true ;//要把flag还原为true
	}
}
if(arr[i] == ')') { //如果遍历到的字符为')',则说明有括号,栈中最上面的两个元素依次出栈,求出的表达式入栈
	int m = stack.pop();
	int n = stack.pop();
	int result = fun(n,m) ;//先出栈的元素放到后面,因为栈是先进后出的
	stack.push(result) ;
}
}
System.out.println(stack.pop()) ; //打印栈底元素就是最终结果
}
//求解表达式的函数
public static int fun(int x, int y) {
return a * x + b * y ;
}
}

Here Insert Picture Description
Algorithm thinking: this question is examined expression of push and pop question, it must first be noted that the stack is a last-out , the expression of this question will enter into a string, and then stored in an array of characters, and then traverse the array of characters, when traversed minus, the latter need to be negative again into the stack number is multiplied by -1, and if after a positive integer directly into the stack, when traversing to the right bracket, then the fun element of the stack performs functions the result then into the stack, the stack and forth, until the stack, leaving the last element, print stack bottom element is the result of!

Published 43 original articles · won praise 26 · views 8812

Guess you like

Origin blog.csdn.net/nuist_NJUPT/article/details/105011645