PAT-L1-009 N个数求和
2018-03-16 17:42
204 查看
本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。
输入格式:
输入第一行给出一个正整数N(<=100)。随后一行按格式“a1/b1 a2/b2 …”给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。
输出格式:
输出上述数字和的最简形式 —— 即将结果写成“整数部分 分数部分”,其中分数部分写成“分子/分母”,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。
注意各种负数的情况,和分子为0的情况,以及用long。
输入格式:
输入第一行给出一个正整数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; 4000 } 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); } }
相关文章推荐
- L1-009. N个数求和 - PAT
- PAT-L1-009. N个数求和
- PAT L1-009. N个数求和
- L1-009. N个数求和-PAT团体程序设计天梯赛GPLT
- PAT L1-009. N个数求和 模拟
- PAT L1-009. N个数求和(辗转相除法,浮点和输出注意)
- PAT L1 009 N个数求和
- PAT-L1-009. N个数求和
- L1-009. N个数求和-PAT团体程序设计天梯赛
- PAT-团体程序设计天梯赛-练习集-L1-009. N个数求和
- PAT L1-009. N个数求和
- PAT - 天梯赛 L1-009 N个数求和
- PAT练习集之20分题-L1-009. N个数求和
- Java - PAT - L1-009. N个数求和
- PAT 天梯赛 L1-009 N个数求和
- PAT-L1-009. N个数求和(辗转相除法应用)
- 【题解搬运】PAT_L1-009 N个数求和
- PAT 天梯赛 L1-009 N个数求和
- PAT L1-009. N个数求和 分数求和 struct重载
- L1-009. N个数求和