592 分数加减运算(中等)

简介:

image-20221030163814157

解题思路:把握住一点,利用循环依次往后乘,这个题有思路但是不知道怎么写代码。下面是官方的代码。

#
# @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);

    }
};
相关文章
|
23天前
|
算法 测试技术 C#
【位运算】【 数学】【 哈希映射】2857. 统计距离为 k 的点对
【位运算】【 数学】【 哈希映射】2857. 统计距离为 k 的点对
LeetCode-592 分数加减运算
LeetCode-592 分数加减运算
|
23天前
leetcode-592:分数加减运算
leetcode-592:分数加减运算
22 0
|
C++
C++ 计算斐波那契数列第100万项的精确整数值
C++ 计算斐波那契数列第100万项的精确整数值
73 0
|
C++
C++ 超大整数相加、相乘的精确求解,以及10000的阶乘
C++ 超大整数相加、相乘的精确求解,以及10000的阶乘
83 0
05:计算分数的浮点数值
05:计算分数的浮点数值
186 0
LeetCode每日一题——592. 分数加减运算
给定一个表示分数加减运算的字符串 expression ,你需要返回一个字符串形式的计算结果。
91 0
7-2 一元多项式的乘法与加法运算 (20 分)
7-2 一元多项式的乘法与加法运算 (20 分)
109 0
L1-080 乘法口诀数列 (20 分)
L1-080 乘法口诀数列 (20 分)
194 0

热门文章

最新文章