思路:

数据结构中,栈可以解决运算的问题。利用压栈和弹栈操作实现(这里用队列模拟)。具体的:

遇到乘除号,弹出栈顶元素,将计算结果压入栈中。遇到加减号,将后面的数一起压入栈中。

注意:

substring方法前闭后开,substring(i, i + 2)取的是i和i+1。

在ASCII码里'0'对应的刚好是48的二进制码,所以用字符串减去'0'即为整数。

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[n];
sc.nextLine();
for (int i = 0; i < n; i++) {
s[i] = sc.nextLine();//存储算式
}
int[] stack = new int[4];//定义栈
for (String str : s) {
int count = 0;
int result = 0;
stack[0] = str.charAt(0) - '0';//将第一个数存入栈中
for (int i = 1; i < 7; i += 2) {//从第一个运算符号开始扫描所有运算符
if (str.charAt(i) == 'x') {//遇到乘除号弹出栈顶元素并将结果计算后压入栈顶
stack[count] = stack[count] * (str.charAt(i + 1) - '0');
} else if (str.charAt(i) == '/') {
stack[count] = stack[count] / (str.charAt(i + 1) - '0');
} else {//遇到加减号将数字连同符号一起压入栈顶
stack[++count] = Integer.parseInt(str.substring(i, i + 2));
}
}
for (; count >= 0; count--) {//将所有元素弹栈并相加
result += stack[count];
}
if (result == 24)//判断最终结果是否为24
System.out.println("Yes");
else
System.out.println("No");
}
sc.close();
}
}

最新文章

  1. Sublime Text 3汉化中文版
  2. 阻止Ajax多次提交
  3. Debian 入门安装与配置1
  4. Useful related java API for Android
  5. c#基础编程—泛型
  6. IT人士的职业规范——凝视
  7. [译]ASP.NET Core 2.0 全局配置项
  8. Docker学习笔记 - Docker的守护进程
  9. 实现ssr服务端渲染
  10. 如何在WIN10内置Ubuntu中有多个terminal
  11. Python3 多线程、多进程
  12. macOS Sierra上面的php开发环境安装
  13. 解决apache httpd列出目录列表中文乱码问题
  14. linux中 bashrc文件的alias添加快捷命令
  15. POJ - 1850 Code(组合数学)
  16. 小白学习 Redis 数据库日记(2017-06-13)
  17. 清除linux服务器缓存 clean.sh
  18. 微软职位内部推荐-Senior Dev Lead - SharePoint
  19. 【LOJ】#2084. 「NOI2016」网格
  20. [JZOJ4786]小a的强迫症

热门文章

  1. what to do in next ten years
  2. CCF 201703-4 地铁修建(最小生成树)
  3. CodeForces - 862C Mahmoud and Ehab and the xor(构造)
  4. Koa2+mongoose
  5. 刷题21. Merge Two Sorted Lists
  6. OLTP和OLAP区别详解
  7. MQTT 协议学习:004-MQTT建立通信与 CONNECT 、CONNACK 报文
  8. Acwing199 余数之和
  9. 2018年Android面试题含答案--适合中高级(下)(转)
  10. C++实现单链表的12种基本操作