当前位置:网站首页>Calculate the result of a string formula

Calculate the result of a string formula

2022-06-09 12:05:00 N. LAWLIET

problem
Given a string str,str Represents a formula
There may be integers in the formula , Add, subtract, multiply and divide , Left and right parentheses and other symbols
Returns the formula calculation result , The difficulty is that parentheses can have many layers ?
Example
str= 48*((70-65)-43)+8*1 Return results -1816
thought
Use the stack to add elements to the stack , The start of the stack starts with the left parenthesis , Stop again , Do not include parentheses , When there is no bracket, the end of the left bracket is encountered , Then the inner use in brackets creates a new stack , And give priority to .
Code

public class Code01_ExpressionCompute {
    
	
	public static int computenum(String str) {
    
		return process(str.toCharArray(),0)[0];
	}

	private static int[] process(char[] charArray, int i) {
    
		LinkedList<String> que =  new LinkedList<String>();
		int num = 0;
		int[] bar = null;
		while(i<charArray.length&&charArray[i]!=')') {
    
			if(charArray[i]>='0'&&charArray[i]<='9') {
    
				num = num*10 +charArray[i++]-'0';
			}else if(charArray[i]!='(') {
    
				addnum(que,num);
				que.addLast(String.valueOf(charArray[i++]));
				num = 0;
			}else {
    
				bar = process(charArray, i+1);
				num = bar[0];
				i = bar[1]+1;
			}
		}
		addnum(que, num);
		return new int[] {
    getnum(que),i};
	}

	private static void addnum(LinkedList<String> que, int num) {
    
		if(!que.isEmpty()) {
    
			String top = que.pollLast();
			int cur = 0;
			if(top.equals("+")||top.equals("-")) {
    
				que.addLast(top);
			}else {
    
				cur = Integer.valueOf(que.pollLast());
				num = top.equals("*")?2cur*num:(cur/num);
			}
		}
		que.addLast(String.valueOf(num));
	}
	private static int getnum(LinkedList<String> que) {
    
		int res = 0;
		int num = 0;
		String cur = null;
		boolean add = true;
		while(!que.isEmpty()) {
    
			cur = que.pollFirst();
			if(cur.equals("+")) add = true;
			else if(cur.equals("-")) add = false;
			else {
    
				num = Integer.valueOf(cur);
				res += add? num:(-num);
			}
		}
		return res;
	}
	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()) {
    
			String str = scanner.nextLine();
			int ans = computenum(str);
			System.out.println(ans);
		}

	}

}

原网站

版权声明
本文为[N. LAWLIET]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091123562508.html