解题思路:把握住一点,利用循环依次往后乘,这个题有思路但是不知道怎么写代码。下面是官方的代码。
#
# @lc app=leetcode.cn id=592 lang=python3
#
# [592] 分数加减运算
#
# @lc code=start
class Solution:
def fractionAddition(self, expression: str) -> str:
x, y = 0, 1 # 定义分子,分母
i, n = 0, len(expression)
while i < n:
# 读取分子
x1, sign = 0, 1
if expression[i] == '-' or expression[i] == '+':
if expression[i] == '-':
sign = -1
i += 1
while i < n and expression[i].isdigit():
#表示十进制数太妙了
x1 = x1*10+int(expression[i])
i += 1
x1 = sign*x1
i += 1
# 读取分母
y1 = 0
while i < n and expression[i].isdigit():
y1 = y1*10+int(expression[i])
i += 1
x = x*y1+x1*y
y *= y1
if x == 0:
return "0/1"
# gcd函数取最大公约数
g = gcd(abs(x), y)
return f"{x//g}/{y//g}"
# @lc code=end
//C++版本代码 学习使用C++写代码
class Solution {
public:
string fractionAddition(string expression) {
long long x=0,y=1;//分子和分母
int i=0,n=expression.size();
while (i<n){
//读取分子
long long x1=0,sign=1;
while (expression[i]=='-'||expression[i]=='+'){
sign=expression[i]=='-'? -1:1;
i++;
}
while(i<n && isdigit(expression[i])){
x1=x1*10+expression[i]-'0';
i++;
}
x1=sign*x1;
i++;
//读取分母
long long y1=0;
while(i<n && isdigit(expression[i])){
y1=y1*10+expression[i]-'0';
i++;
}
x=x*y1+x1*y;
y*=y1;
}
if(x==0){
return "0/1";
}
long long g=gcd(abs(x),y);//获取最大公约数
return to_string(x/g)+"/"+to_string(y/g);
}
};