当前位置:网站首页>Force deduction solution summary 592 fraction addition and subtraction
Force deduction solution summary 592 fraction addition and subtraction
2022-07-27 20:56:00 【Lost summer】
Directory links :
Force buckle programming problem - The solution sums up _ Share + Record -CSDN Blog
GitHub Synchronous question brushing items :
https://github.com/September26/java-algorithms
Original link :
describe :
Given a string representing the addition and subtraction of fractions expression , You need to return a string calculation .
This result should be an irreducible score , The simplest fraction . If the final result is an integer , for example 2, You need to convert it into fractions , Its denominator is 1. So in the above example , 2 Should be converted to 2/1.
Example 1:
Input : expression = "-1/2+1/2"
Output : "0/1"
Example 2:
Input : expression = "-1/2+1/2+1/3"
Output : "1/3"
Example 3:
Input : expression = "1/3-1/2"
Output : "-1/6"
Tips :
Input and output strings contain only '0' To '9' The number of , as well as '/', '+' and '-'.
The input and output fractional formats are ± molecular / The denominator . If the first score entered or the score output is a positive number , be '+' Will be omitted .
Input contains only the legal minimum score , The range of the numerator and denominator of each fraction is [1,10]. If the denominator is 1, Which means that the score is actually an integer .
The range of scores entered is [1,10].
The molecular and denominator guarantees of the final result are 32 Valid integers in the range of bit integers .
source : Power button (LeetCode)
link :https://leetcode.cn/problems/fraction-addition-and-subtraction
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Their thinking :
* Their thinking : * Split the string into nodes one by one , Each node contains molecules , The denominator , And the operator . * If the first node starts with a negative number, the operator is negative , Otherwise, it is positive . * Calculate these nodes one by one from scratch , If the denominators are equal, calculate directly , Otherwise, multiply the denominator . The final result is the value of the node obtained at the end of the division process .
Code :
public class Solution592 {
public String fractionAddition(String expression) {
int lastIndex = 0;
List<Node> list = new ArrayList<>();
char[] chars = expression.toCharArray();
for (int i = 0; i <= chars.length; i++) {
if (i == expression.length()) {
Node paser = paser(expression.substring(lastIndex, i));
list.add(paser);
continue;
}
int value = chars[i];
if (value == '-' || value == '+') {
Node paser = paser(expression.substring(lastIndex, i));
if (paser != null) {
list.add(paser);
}
lastIndex = i;
continue;
}
}
Node lastNode = new Node();
for (int i = 0; i < list.size(); i++) {
Node node = list.get(i);
lastNode = calculation(lastNode, node);
}
if (lastNode.current == 0) {
lastNode.current2 = 1;
} else {
// Fractional calculation
int i = 2;
while (i <= Math.abs(lastNode.current)) {
if (lastNode.current % i == 0 && lastNode.current2 % i == 0) {
lastNode.current /= i;
lastNode.current2 /= i;
i = 2;
continue;
}
i++;
}
}
return lastNode.current + "/" + lastNode.current2;
}
private Node paser(String str) {
Node node = new Node();
if (str.length() == 0) {
return null;
}
int index = 0;
int lastIndex = 0;
char[] chars = str.toCharArray();
while (index <= str.length()) {
if (index == str.length()) {
node.current = Integer.parseInt(str.substring(lastIndex));
break;
}
int value = chars[index++];
if (value == '-') {
node.isAdd = false;
lastIndex++;
continue;
}
if (value == '/') {
node.current = Integer.parseInt(str.substring(lastIndex, index - 1));
node.current2 = Integer.parseInt(str.substring(index));
break;
}
}
return node;
}
private Node calculation(Node node1, Node node2) {
Node node = new Node();
if (node1.current2 == node2.current2) {
node.current = node2.isAdd ? node1.current + node2.current : node1.current - node2.current;
node.current2 = node1.current2;
return node;
}
int i1 = node1.current * node2.current2;
int i2 = node2.current * node1.current2;
node.current = node2.isAdd ? i1 + i2 : i1 - i2;
node.current2 = node1.current2 * node2.current2;
return node;
}
public static class Node {
boolean isAdd = true;
int current = 0;// molecular
int current2 = 1;// The denominator
}
}边栏推荐
- Introduction to rk3399 platform introduction to proficient series (Introduction) 21 day learning challenge
- Automatic test solution based on ATX
- IPv4/IPv6、DHCP、网关、路由
- Management of user organization structure
- 金仓数据库 Oracle至KingbaseES迁移最佳实践(2. 概述)
- Analysis on the optimization of login request in IM development of instant messaging mobile terminal
- 推荐一款强大的搜索工具Listary
- 金仓数据库 KingbaseES异构数据库移植指南 (2. 概述)
- 品牌列表案例
- 【防抖与节流】
猜你喜欢

Management of user organization structure

Where is the program?

品牌列表案例
![Laboratory management system implemented by SSM framework +jsp [source code + database + system paper]](/img/2e/64af546c58f3dc517cdae304daa671.png)
Laboratory management system implemented by SSM framework +jsp [source code + database + system paper]

【Dart】一门为跨端开发而生的编程语言

Why are TS slice files generated when easycvr platform turns off video recording?

一周活动速递|深入浅出第8期;Meetup成都站报名进行中

Analysis on the optimization of login request in IM development of instant messaging mobile terminal

How to translate the address in the program?

knife4j通过js动态刷新全局参数
随机推荐
Source Insight 4.0使用介绍
14天鸿蒙设备开发实战-第七章 设备联网上云 学习笔记
MySQL design optimization generates columns
Arduino development (II)_ RGB light control method based on Arduino uno development board
品牌列表案例
JVS私有化部署启动失败处理方案
JVs official account login configuration
Analysis on the optimization of login request in IM development of instant messaging mobile terminal
Innovative cases | the growth strategy of digitalization of local life services and upgrading of Gaode brand
vi工作模式(3种)以及模式切换(转换)
Best practices for Oracle kingbasees migration of Jincang database (4. Oracle database migration practice)
Rk3399 platform development series explanation (process part) 15.36, understanding process and collaboration process
程序中的地址如何转换?
你了解数据同步吗?
Onion group joined hands with oceanbase to realize distributed upgrading, and global data has achieved cross cloud integration for the first time
R语言使用epiDisplay包的power.for.2p函数进行效用分析 ( 效能分析、Power analysis)、给定两个样本的比例值(proportions)、样本量计算效用值
go --- air自动重新编译
获取委托中注册的方法
未定义变量 “Lattice“ 或类 “Lattice.latticeEasy“(Matlab)
R语言使用dplyr包进行数据聚合统计计算滑动窗口统计值(Window Statistics)、计算滑动分组均值(mean)并合并生成的统计数据到原数据集中