201903-2 二十四点 Java
2024-08-31 20:22:20
思路:
数据结构中,栈可以解决运算的问题。利用压栈和弹栈操作实现(这里用队列模拟)。具体的:
遇到乘除号,弹出栈顶元素,将计算结果压入栈中。遇到加减号,将后面的数一起压入栈中。
注意:
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();
}
}
最新文章
- Sublime Text 3汉化中文版
- 阻止Ajax多次提交
- Debian 入门安装与配置1
- Useful related java API for Android
- c#基础编程—泛型
- IT人士的职业规范——凝视
- [译]ASP.NET Core 2.0 全局配置项
- Docker学习笔记 - Docker的守护进程
- 实现ssr服务端渲染
- 如何在WIN10内置Ubuntu中有多个terminal
- Python3 多线程、多进程
- macOS Sierra上面的php开发环境安装
- 解决apache httpd列出目录列表中文乱码问题
- linux中 bashrc文件的alias添加快捷命令
- POJ - 1850 Code(组合数学)
- 小白学习 Redis 数据库日记(2017-06-13)
- 清除linux服务器缓存 clean.sh
- 微软职位内部推荐-Senior Dev Lead - SharePoint
- 【LOJ】#2084. 「NOI2016」网格
- [JZOJ4786]小a的强迫症
热门文章
- what to do in next ten years
- CCF 201703-4 地铁修建(最小生成树)
- CodeForces - 862C Mahmoud and Ehab and the xor(构造)
- Koa2+mongoose
- 刷题21. Merge Two Sorted Lists
- OLTP和OLAP区别详解
- MQTT 协议学习:004-MQTT建立通信与 CONNECT 、CONNACK 报文
- Acwing199 余数之和
- 2018年Android面试题含答案--适合中高级(下)(转)
- C++实现单链表的12种基本操作