top1编程
← 返回题目
题解

计算分数

1 条题解

  • 0
    @ 2026-10-21 1:37:49

    1. 解题思路

    逐项解析符号、分子和分母,通分相加减后立即用最大公约数约分。最终分母为1时输出整数,否则输出分数。

    2. 坑点和注意事项

    表达式≤100字符、分子分母≤1000,题保逐次约分结果在int内。临时乘法用long long,gcd取分子绝对值,0约成0/1。

    3. 复杂度

    • 时间复杂度:O(|s| log V)。
    • 空间复杂度:O(|s|)。
    /*
    思路:逐项解析符号、分子和分母,通分相加减后立即用最大公约数约分。最终分母为1时输出整数,否则输出分数。
    关键规则与坑点:表达式≤100字符、分子分母≤1000,题保逐次约分结果在int内。临时乘法用long long,gcd取分子绝对值,0约成0/1。
    时间复杂度:O(|s| log V)。空间复杂度:O(|s|)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        string s;
        cin >> s;
        long long a = 0, b = 1;
        size_t i = 0;
        while (i < s.size())
        {
            int sign = 1;
            if (s[i] == '+' || s[i] == '-')
            {
                if (s[i] == '-')
                    sign = -1;
                i++;
            }
            long long x = 0, y = 0;
            while (i < s.size() && isdigit(s[i]))
                x = x * 10 + s[i++] - '0';
            i++;
            while (i < s.size() && isdigit(s[i]))
                y = y * 10 + s[i++] - '0';
            a = a * y + sign * x * b;
            b *= y;
            long long g = gcd(llabs(a), b);
            a /= g;
            b /= g;
        }
        cout << a;
        if (b != 1)
            cout << '/' << b;
        cout << "\n";
    }
    
    • 1