当前位置:网站首页>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);
}
};
边栏推荐
猜你喜欢

ECCV 2022丨轻量级模型架ParC-Net 力压苹果MobileViT代码和论文下载

Shallow reading of shared lock source code of abstractqueuedsynchronizer (AQS)

Hongke shares | how to test and verify complex FPGA designs (1) -- entity or block oriented simulation

分享一些你代码更好的小建议,流畅编码提搞效率

10 frequently asked JVM questions in interviews

【经验】通过跳板机远程连接内网服务器的相关配置

王树尧老师运筹学课程笔记 04 线性代数基础

【论文阅读 | cryoET】Gum-Net:快速准确的3D Subtomo图像对齐和平均的无监督几何匹配

竣达技术 | 适用于”日月元”品牌UPS微信云监控卡

【冷冻电镜|论文阅读】子断层平均 M 软件解读:Multi-particle cryo-EM refinement with M
随机推荐
Difference between CNAME record and a record
微信小程序的反编译
模拟卷Leetcode【普通】093. 复原 IP 地址
关于SQL Server语句入门级应用阶段性学习——找工作必备(一)
Biased lock, lightweight lock test tool class level related commands
量子机器学习中的安全性问题
Understanding of access, hybrid and trunk modes
Not so simple singleton mode
联邦学习后门攻击总结(2019-2022)
Software definition boundary SDP
Teacher Wang Shuyao's notes on operations research 09 linear programming and simplex method (Application of simplex table)
【冷冻电镜】Relion4.0——subtomogram教程
Use of callable
线程 - 线程安全 - 线程优化
基于Matlab解决线性规划问题
Windows 上 php 7.4 连接 oracle 配置
Hongke share | let you have a comprehensive understanding of "can bus error" (III) -- can node status and error counter
Invalid access control
分享一些你代码更好的小建议,流畅编码提搞效率
Analysis of four isolation levels of MySQL things
