当前位置:网站首页>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);
}
};边栏推荐
- 每日一题:两数之和
- KDD‘21推荐系统离散特征表征无embedding table Learning to Embed Categorical Features without Embedding Tables for
- Explore CSAPP Experiment 2-bomb lab-Section 1
- Microsoft Office 2019 软件下载安装详细教程!
- 查询表中开始日期与结束日期
- 镜像站收集
- 报错500,“message“: “nested exception is org.apache.ibatis.binding.BindingException: 解决记录
- 《痞子衡嵌入式半月刊》 第 59 期
- 哎,这要人老命的缓存一致问题啊
- Mirror stand to collect
猜你喜欢

KDD 2020 | 深入浅出优势特征蒸馏在淘宝推荐中的应用

主流的深度学习推理架构有哪些呢?

《痞子衡嵌入式半月刊》 第 59 期

You are a first-class loser, you become a first-class winner

FP6606ACAW4 TQFN-20L (3mmx3mm) USB双端口充电控制器 百盛电子代理

Security business revenue growth rate exceeds 70% 360 builds digital security leader

浅谈在线编辑器中增量编译技术的应用

S7-200SMART中定时器的使用方法和常见注意事项汇总

真正懂经营管理的CIO具备哪些特质

FP6606CMP5 CPC-16L USB类型-C和PD充电控制器 百盛电子代理商
随机推荐
LeetCode167:有序数组两数之和
FP6606CMP5 CPC-16L USB类型-C和PD充电控制器 百盛电子代理商
Discuz magazine/news report template (jeavi_line) UTF8-GBK template
You are a first-class loser, you become a first-class winner
[HarekazeCTF2019] Avatar Uploader 1
KDD‘21推荐系统离散特征表征无embedding table Learning to Embed Categorical Features without Embedding Tables for
Mongoose module
华为无线设备配置Mesh业务
esp32系列(5):esp32 蓝牙架构学习
论文阅读之《Underwater scene prior inspired deep underwater image and video Enhancement (UWCNN)》
Oracle动态监听与静态监听详解
Microsoft Office 2019 软件下载安装详细教程!
Navisworks切换语言
Wanhua chemical fine chemical industry innovation product assembly
Lotus explodes the block failed
(17)[系统调用]追踪系统调用(0环)
Mysql进阶优化篇01——四万字详解数据库性能分析工具(深入、全面、详细,收藏备用)
592. Fraction Addition and Subtraction
Error occurred while trying to proxy request项目突然起不来了
【综合类型第 34 篇】喜讯!喜讯!!喜讯!!!,我在 CSDN 的第一个实体铭牌