当前位置:网站首页>592. Fraction Addition and Subtraction
592. Fraction Addition and Subtraction
2022-07-30 17:12:00 【soO_007】
题目:
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.
The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 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"
Constraints:
- The input string only contains
'0'to'9','/','+'and'-'. So does the output. - Each fraction (input and output) has the format
±numerator/denominator. If the first input fraction or the output is positive, then'+'will be omitted. - The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range
[1, 10]. If the denominator is1, it means this fraction is actually an integer in a fraction format defined above. - The number of given fractions will be in the range
[1, 10]. - The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
思路:
单纯模拟题,Two points need to be grasped,One is the greatest common divisor,You can use tossing and dividing,但是要注意-1,比较的时候需要用abs;另一个是
.First you need four numbers,upRepresents the current number numerator,downIndicates the denominator of the current number,The current number isup / down,初始化肯定是0,But avoid the denominator of 0,我们把up初始化为0,down初始化为1,不影响结果;同理使用nextup和nextdownRecord the next number,用signRecord the sign of the next number,初始化为1即可.An additional number is requiredcur,记录当前数字,因为可能是111,then each carry is required,即每次cur * 10 + 当前expression[i]的int即可.之后遍历expression,Each time a plus or minus sign is encountered, a round of calculations is performed,First if the denominator of the next number is 0,we assign1,防止分母为0.之后为nextup计算符号,Apply formula to get new oneup和down即可.Remember to reset herecur和sign,因为signis the plus or minus representing the next number,因此当前expression[i]The plus and minus signs are when the new one is calculatedup和downAssigned latersign.Finally add the last number after the traversal is complete,再得出gcd,对up和down都除以最大公约数,再转成string就是答案了.
代码:
class Solution {
public:
string fractionAddition(string expression) {
int up = 0, down = 1;
int i = 0, sign = 1;
int nextup = 0, nextdown = 1;
int cur = 0;
while (i < expression.size()) {
if (expression[i] == '-') {
nextdown = cur == 0 ? 1 : cur;
nextup *= sign;
up = up * nextdown + down * nextup;
down = down * nextdown;
sign = -1;
cur = 0;
} else if (expression[i] == '+') {
nextdown = cur == 0 ? 1 : cur;
nextup *= sign;
up = up * nextdown + down * nextup;
down = down * nextdown;
sign = 1;
cur = 0;
} else if (expression[i] == '/') {
nextup = cur;
cur = 0;
} else {
cur = cur * 10 + (expression[i] - '0');
}
i++;
}
nextdown = cur == 0 ? 1 : cur;
nextup *= sign;
up = up * nextdown + down * nextup;
down = down * nextdown;
sign = up >= 0 ? 1 : -1;
int g = abs(gcd(up, down));
up /= g;
down /= g;
string ans = to_string(up) + '/' + to_string(down);
return ans;
}
private:
int gcd(int a, int b) {
if (abs(a) < abs(b))
return gcd(b, a);
if (b == 0)
return a;
return gcd(a % b, b);
}
};边栏推荐
- FP6606CMP5 CPC-16L USB类型-C和PD充电控制器 百盛电子代理商
- shell快速移植
- 微信小程序picker滚动选择器使用详解
- 论文阅读之《DeepIlluminance: Contextual IlluminanceEstimation via Deep Neural Networks》
- Redis缓存穿透-热点缓存并发重建-缓存与数据库双写不一致-缓存雪崩
- Is it reliable to work full-time in self-media?
- 大厂面试官眼中的好简历到底长啥样
- SLIM: Sparse Linear Methods (TopN推荐)
- .NET 6.0中使用Identity框架实现JWT身份认证与授权
- Promise入门到精通(1.5w字详解)
猜你喜欢

【综合类型第 34 篇】喜讯!喜讯!!喜讯!!!,我在 CSDN 的第一个实体铭牌

JMeter笔记4 | JMeter界面介绍

华为无线设备配置Mesh业务

2022-07-30 Androd 进入深度休眠后把WIFI给关掉,唤醒之后重新打开WIFI

Mongoose module

What does a good resume look like in the eyes of a big factory interviewer?

FP6600QSO SOP-8 USB专用充电端口控制器 用于快充电协议和QC2.0/3.0

Excel导入和导出
![[HarekazeCTF2019]Avatar Uploader 1](/img/2c/6dde7b8d34ba0deb334b4283e1e30e.png)
[HarekazeCTF2019]Avatar Uploader 1

论文阅读 (63):Get To The Point: Summarization with Pointer-Generator Networks
随机推荐
MySQL超详细安装教程 手把手教你安装MySQL到使用MySQL 最简单的MySQL安装方式,这种方式装,卸载也简单
代码越写越乱?那是因为你没用责任链
阿里SIM-基于检索的用户行为兴趣CTR模型(Search-based user Interest Model(SIM))
数据库的三大范式
《痞子衡嵌入式半月刊》 第 59 期
lotus 爆块失败
你是这样的volatile,出乎意料
Research on intelligent charging strategy of matlab simulink lithium-ion battery
浅谈在线编辑器中增量编译技术的应用
Error occurred while trying to proxy request项目突然起不来了
Tensorflow模型量化(Quantization)原理及其实现方法
olap——入门ClickHouse
Lotus 1.16.0 minimum snapshot export import
Redis缓存穿透-热点缓存并发重建-缓存与数据库双写不一致-缓存雪崩
主流的深度学习推理架构有哪些呢?
Dive deep on Netflix‘s recommender system(Netflix推荐系统是如何实现的?)
bert-base调试心得
升级Win11后不喜欢怎么退回Win10系统?
数据库课程设计大作业大盘点【建议在校生收藏】
SLIM: Sparse Linear Methods (TopN推荐)