当前位置: 首页> 游戏> 单机 > 华强北手机批发商城_公关公司官网_石家庄限号_关键词首页排名代做

华强北手机批发商城_公关公司官网_石家庄限号_关键词首页排名代做

时间:2025/7/15 6:46:18来源:https://blog.csdn.net/LiuYQi/article/details/143064273 浏览次数:0次
华强北手机批发商城_公关公司官网_石家庄限号_关键词首页排名代做

考核内容:

在指定的题库中自主选择不少于 15 道算法题并完成解题,其中题目难度分配如下:

  • 简单题不少于 10 道
  • 中等题不少于 4 道
  • 困难题不少于 1 道

解答代码

5.简单四则运算 (中)

代码实现:

import java.util.Stack;public class Main {public static int solution(String expression) {Stack<Integer> numStack = new Stack<>();Stack<Character> opStack = new Stack<>();// 遍历表达式for (int i = 0; i < expression.length(); i++) {char c = expression.charAt(i);// 如果是数字,将其转换为整数并压入数字栈if (Character.isDigit(c)) {int num = 0;while (i < expression.length() && Character.isDigit(expression.charAt(i))) {num = num * 10 + (expression.charAt(i) - '0');i++;}i--;numStack.push(num);}// 如果是左括号,直接压入运算符栈else if (c == '(') {opStack.push(c);}// 如果是右括号,进行计算直到遇到左括号else if (c == ')') {while (opStack.peek() != '(') {char op = opStack.pop();int num2 = numStack.pop();int num1 = numStack.pop();if (op == '+') {numStack.push(num1 + num2);} else if (op == '-') {numStack.push(num1 - num2);} else if (op == '*') {numStack.push(num1 * num2);} else if (op == '/') {numStack.push(num1 / num2);}}opStack.pop();}// 如果是运算符,根据优先级进行处理else if (isOperator(c)) {while (!opStack.isEmpty() && precedence(c) <= precedence(opStack.peek())) {char op = opStack.pop();int num2 = numStack.pop();int num1 = numStack.pop();if (op == '+') {numStack.push(num1 + num2);} else if (op == '-') {numStack.push(num1 - num2);} else if (op == '*') {numStack.push(num1 * num2);} else if (op == '/') {numStack.push(num1 / num2);}}opStack.push(c);}}// 处理剩余的运算符while (!opStack.isEmpty()) {char op = opStack.pop();int num2 = numStack.pop();int num1 = numStack.pop();if (op == '+') {numStack.push(num1 + num2);} else if (op == '-') {numStack.push(num1 - num2);} else if (op == '*') {numStack.push(num1 * num2);} else if (op == '/') {numStack.push(num1 / num2);}}// 返回数字栈的栈顶元素即为结果return numStack.pop();}// 判断是否为运算符public static boolean isOperator(char c) {return c == '+' || c == '-' || c == '*' || c == '/';}// 定义运算符的优先级public static int precedence(char op) {if (op == '+' || op == '-') {return 1;} else if (op == '*' || op == '/') {return 2;}return -1;}public static void main(String[] args) {// You can add more test cases hereSystem.out.println(solution("1+1") == 2);System.out.println(solution("3+4*5/(3+2)") == 7);System.out.println(solution("4+2*5-2/1") == 12);System.out.println(solution("(1+(4+5+2)-3)+(6+8)") == 23);}
}

运行结果在这里插入图片描述

关键字:华强北手机批发商城_公关公司官网_石家庄限号_关键词首页排名代做

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: