PAT-L1-009 N个数求和

本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。

输入格式:

输入第一行给出一个正整数N(<=100)。随后一行按格式“a1/b1 a2/b2 …”给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。

输出格式:

输出上述数字和的最简形式 —— 即将结果写成“整数部分 分数部分”,其中分数部分写成“分子/分母”,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。

注意各种负数的情况,和分子为0的情况,以及用long。

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        // InputReader reader = new InputReader();
        int n = reader.nextInt();
        if (n == 0) {
            System.out.println(0);
            return;
        }
        long x = 0;
        long y = 0;
        for (int i = 0; i < n; i++) {
            String[] input = reader.next().split("/");
            long a = Long.parseLong(input[0]);
            long b = Long.parseLong(input[1]);
            if (y != b && y != 0) {
                x *= b;
                a *= y;
                long temp = y * b;
                y = temp;
                b = temp;
            }
            // System.out.println(a + "/" + b);
            x += a;
            y = b;
            long gcd = GCD(x, y);
            x /= gcd;
            y /= gcd;
            if (y < 0 && x > 0) {
                y = Math.abs(y);
                x = x * -1;
            }
            if (x == 0) {
                y = 0;
            }
        }
        long res = 0;
        if (y == 0) {
            System.out.println(0);
            return;
        }
        if (Math.abs(x) >= Math.abs(y)) {
            res = x / y;
            x = x % y;
            System.out.print(res);
        }
        if (x == 0) {
            return;
        }
        if (Math.abs(res) > 0) {
            System.out.print(" ");
        }
        System.out.println(x + "/" + y);
    }

    public static long GCD(long x, long y) {
        return y == 0 ? x : GCD(y, x % y);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值