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

Hongke shares | testing and verifying complex FPGA design (2) -- how to perform global oriented simulation in IP core

吴恩达老师机器学习课程笔记 02 单变量线性回归

线程 - 线程安全 - 线程优化

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

【冷冻电镜|论文阅读】子断层平均 M 软件解读:Multi-particle cryo-EM refinement with M

王树尧老师运筹学课程笔记 07 线性规划与单纯形法(标准型、基、基解、基可行解、可行基)

Embedding understanding + code

循环神经网络RNN

Unity免费元素特效推荐

NeuralCF-神经协同过滤网络
随机推荐
Hongke shares | how to test and verify complex FPGA designs (1) -- entity or block oriented simulation
SS command details
LDAP brief description and unified authentication description
猜数字//第一次使用生成随机数
SSH免密登录-两台虚拟机建立免密通道 双向信任
Use of callable
Teacher Wu Enda's machine learning course notes 00 are written in the front
IDEA找不到Database解决方法
如何优雅的写 Controller 层代码?
MySql基础知识(高频面试题)
阿里一面,给了几条SQL,问需要执行几次树搜索操作?
Teacher Wu Enda machine learning course notes 01 introduction
模拟卷Leetcode【普通】093. 复原 IP 地址
Salesforce中过滤器Filter使用的相对日期
ECCV 2022丨轻量级模型架ParC-Net 力压苹果MobileViT代码和论文下载
NeuralCF-神经协同过滤网络
基于Matlab解决线性规划问题
Teacher wangshuyao wrote the notes of operations research course 00 in the front
Why does 5g N2 interface control plane use SCTP protocol?
王树尧老师运筹学课程笔记 03 KKT定理
