当前位置:网站首页>Leetcode-592: fraction addition and subtraction
Leetcode-592: fraction addition and subtraction
2022-07-29 06:57:00 【Chrysanthemum headed bat】
leetcode-592: Fractional addition and subtraction
subject
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"

Problem solving
Method 1 : simulation
class Solution {
public:
string fractionAddition(string expression) {
long long a=0,b=1;// molecular , The denominator
int index=0,n=expression.size();
while(index<n){
// Read the sign
int sign=1;// If no symbols are encountered , Default positive
if(expression[index]=='+'||expression[index]=='-'){
sign=expression[index]=='+'?1:-1;
index++;
}
// Read molecules
long long a1=0;
while(isdigit(expression[index])){
a1=a1*10+expression[index]-'0';
index++;
}
index++;// skip '/'
// Read denominator
long long b1=0;
while(isdigit(expression[index])){
b1=b1*10+expression[index]-'0';
index++;
}
a1=a1*sign;
a=a*b1+a1*b;
b=b*b1;
}
if(a==0) return "0/1";
long long g=gcd(abs(a),b);// Get the greatest common divisor
return to_string(a/g)+"/"+to_string(b/g);
}
};
边栏推荐
- 没那么简单的单例模式
- Teacher wangshuyao's notes on operations research 05 linear programming and simplex method (concept, modeling, standard type)
- N2 interface of 5g control plane protocol
- Security in quantum machine learning
- Teacher Cui Xueting's course notes on optimization theory and methods 00 are written in the front
- vim文本编辑器的一些使用小技巧
- 吴恩达老师机器学习课程笔记 03 线性代数回顾
- Use of PDO
- 循环神经网络RNN
- Difference between CNAME record and a record
猜你喜欢
随机推荐
【论文阅读】TomoAlign: A novel approach to correcting sample motion and 3D CTF in CryoET
王树尧老师运筹学课程笔记 03 KKT定理
【论文阅读 | 冷冻电镜】RELION 4.0 中新的 subtomogram averaging 方法解读
Software definition boundary SDP
游戏资产的革命
Hongke shares | how to test and verify complex FPGA designs (1) -- entity or block oriented simulation
基于Matlab解决线性规划问题
Ali gave several SQL messages and asked how many tree search operations need to be performed?
Apisik health check test
Pytorch多GPU条件下DDP集群分布训练实现(简述-从无到有)
好文佳句摘录
剑指 Offer II 115:重建序列
吴恩达老师机器学习课程笔记 00 写在前面
Teacher wangshuyao's notes on operations research 02 fundamentals of advanced mathematics
IO流 - File - properties
【笔记】The art of research - (讲好故事和论点)
Idea cannot find a database solution
N2 interface of 5g control plane protocol
Best example of amortized cost
5g service interface and reference point










