当前位置:网站首页>592. Fraction addition and subtraction: introduction to expression calculation
592. Fraction addition and subtraction: introduction to expression calculation
2022-07-28 00:45:00 【Gong Shui Sanye's Diary of writing questions】
Title Description
This is a LeetCode Upper 592. Fractional addition and subtraction , The difficulty is secondary .
Tag : 「 Expression evaluation 」、「 simulation 」
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 , You need to convert it into fractions , Its denominator is . So in the above example , 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 . If the denominator is , Which means that the score is actually an integer . The range of scores entered is . The molecular and denominator guarantees of the final result are Valid integers in the range of bit integers .
Expression evaluation
For convenience , Make expression by s.
Because only + and -, Therefore, there is no need to consider the priority problem , Calculate directly from front to back .
Using variables ans Refers to the result of the calculation process , Process expressions from front to back s, Each time ± molecular / The denominator Get the current operand in the form of ( If it is the first operand of the expression , And positive , Need to manually fill one +).
Assume that the operand currently fetched is num, according to ans To calculate :
if ansFor the empty string , explainnumIs the first operand , Direct willnumAssign a value toansthat will doif ansIt's not empty string , Now calculatenumandansThe result of the calculation is assigned toans
Consider implementing a calculation function String calc(String a, String b) Calculate two operations a and b Result , One of them is ginseng a and b And the return value meet ± molecular / The denominator form .
First, by reading a and b The first character of , Get the positive and negative conditions of the two operands . If it is one positive and one negative , In the form of exchange , Make sure a Is a positive number ,b It's a negative number .
And then through parse Method to disassemble the numerator and denominator of string operands ,parse It can be realized by pointer scanning , Return the result as an array ( The first Bit is a molecular value , The first Digit denominator value ).
Suppose the operands a The corresponding value is , The value of the operands is , Convert it to and , After operation , Then by finding the greatest common divisor gcd To simplify .
Java Code :
class Solution {
public String fractionAddition(String s) {
int n = s.length();
char[] cs = s.toCharArray();
String ans = "";
for (int i = 0; i < n; ) {
int j = i + 1;
while (j < n && cs[j] != '+' && cs[j] != '-') j++;
String num = s.substring(i, j);
if (cs[i] != '+' && cs[i] != '-') num = "+" + num;
if (!ans.equals("")) ans = calc(num, ans);
else ans = num;
i = j;
}
return ans.charAt(0) == '+' ? ans.substring(1) : ans;
}
String calc(String a, String b) {
boolean fa = a.charAt(0) == '+', fb = b.charAt(0) == '+';
if (!fa && fb) return calc(b, a);
long[] p = parse(a), q = parse(b);
long p1 = p[0] * q[1], q1 = q[0] * p[1];
if (fa && fb) {
long r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2);
return "+" + (r1 / c) + "/" + (r2 / c);
} else if (!fa && !fb) {
long r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2);
return "-" + (r1 / c) + "/" + (r2 / c);
} else {
long r1 = p1 - q1, r2 = p[1] * q[1], c = gcd(Math.abs(r1), r2);
String ans = (r1 / c) + "/" + (r2 / c);
if (p1 >= q1) ans = "+" + ans;
return ans;
}
}
long[] parse(String s) {
int n = s.length(), idx = 1;
while (idx < n && s.charAt(idx) != '/') idx++;
long a = Long.parseLong(s.substring(1, idx)), b = Long.parseLong(s.substring(idx + 1));
return new long[]{a, b};
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}
TypeScript Code :
function fractionAddition(s: string): string {
const n = s.length
let ans = ""
for (let i = 0; i < n; ) {
let j = i + 1
while (j < n && s[j] != '+' && s[j] != '-') j++
let num = s.substring(i, j)
if (s[i] != '+' && s[i] != '-') num = "+" + num
if (ans != "") ans = calc(num, ans)
else ans = num
i = j
}
return ans[0] == "+" ? ans.substring(1) : ans
};
function calc(a: string, b: string): string {
const fa = a[0] == "+", fb = b[0] == "+"
if (!fa && fb) return calc(b, a)
const p = parse(a), q = parse(b)
const p1 = p[0] * q[1], q1 = q[0] * p[1]
if (fa && fb) {
const r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2)
return "+" + (r1 / c) + "/" + (r2 / c)
} else if (!fa && !fb) {
const r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2)
return "-" + (r1 / c) + "/" + (r2 / c)
} else {
const r1 = p1 - q1, r2 = p[1] * q[1], c = gcd(Math.abs(r1), r2)
let ans = (r1 / c) + "/" + (r2 / c)
if (p1 > q1) ans = "+" + ans
return ans
}
}
function parse(s: string): number[] {
let n = s.length, idx = 1
while (idx < n && s[idx] != "/") idx++
const a = Number(s.substring(1, idx)), b = Number(s.substring(idx + 1))
return [a, b]
}
function gcd(a: number, b: number): number {
return b == 0 ? a : gcd(b, a % b)
}
Time complexity : Spatial complexity :
snacks & Extra practice
An extra meal is more suitable for the written examination interview 「 Expression evaluation 」 problem : Double stack : General solution of expression calculation problem
Last
This is us. 「 Brush through LeetCode」 The first of the series No.592 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
More, more, more popular 「 written examination / interview 」 Relevant information can be found in the beautifully arranged Gather new bases
This paper is written by mdnice Multi platform Publishing
边栏推荐
- The construction of Yongzhou entry exit inspection laboratory
- Impact of privilege changes on existing connections
- How does JMeter solve the problem of garbled code?
- Jmeter 如何解决乱码问题?
- Map set
- Numpy has no unsqueeze function
- 小程序助力智能家居生态平台
- 592. 分数加减运算 : 表达式计算入门题
- 【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发
- leetcode 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球(中等)
猜你喜欢

Set 数据构造函数

OpenVINO整合TensorFlow实现推理加速
![[bre] software build release automation](/img/c6/daead474a64a9a3c86dd140c097be0.jpg)
[bre] software build release automation

迷惑的单片机矩阵按键

公司7月来了个软件测试工程师,一副毛头小子的样儿,哪想到是新一代卷王...

Ali Er Mian: why do we need to separate databases and tables?

The latest notice of the Chinese Academy of Sciences: abandon the impact factor! The journal zoning table will be published for the "Journal surpassing index"

MFC prompts that this application has requested the runtime to terminate it in an unused way editbox box has been deleted and is still in use

智能便利店带你解锁未来科技购物体验

MATLAB如何将k线图设置为经典红绿配色?
随机推荐
MATLAB | 那些你不得不知道的MATLAB小技巧(四)
CSDN21天学习挑战赛
Selection of FFT sampling frequency and sampling points
2020年一季度可穿戴市场出货量达7260万部,苹果独占近三成市场份额
The second uncle cured my spiritual internal friction and made me angry out of station B
JS event propagation capture stage bubbling stage onclick addeventlistener
View the construction details of Yongzhou dioxin Laboratory
程序员工作中的理性与感性活动及所需的技能素养
JVM memory model
Promoting cloud network integration and building a digital economy: Intel unveiled the 5th Digital China Construction Summit - cloud ecosystem Conference
Basic operations of MySQL database (I) --- Based on Database
How to realize fast recognition of oversized images
ASML推出第一代HMI多光束检测机:速度提升600%,适用于5nm及更先进工艺
英特尔AI实践日第56期 | 探讨行业发展新趋势
MATLAB | MATLAB地形生成:矩形迭代法 · 傅里叶逆变换法 · 分形柏林噪声法
自动推理的逻辑09–自动定理证明
蓝桥杯单片机第十一届国赛程序设计试题
Matlab | those matlab tips you have to know (3)
The server is poisoned - the dish is the original sin
leetcode 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球(中等)