[PAT]1081 Rational Sum (20)

来源:互联网 发布:金投顾软件怎么样 编辑:程序博客网 时间:2024/05/21 06:24

最近在憋小论文,算法题练的会少一点。接下来开始刷PAT甲级题库,十一月份考试。

1081. Rational Sum (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

Input Specification:

Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers "a1/b1 a2/b2 ..." where all the numerators and denominators are in the range of "long int". If there is a negative number, then the sign must appear in front of the numerator.

Output Specification:

For each test case, output the sum in the simplest form "integer numerator/denominator" where "integer" is the integer part of the sum, "numerator" < "denominator", and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

Sample Input 1:
52/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
24/3 2/3
Sample Output 2:
2
Sample Input 3:
31/3 -1/6 1/8
Sample Output 3:
7/24
思路:这道题没有什么特别好的解法,用三个数分别记录分子、分母、带分数整数部分。

然后依次相加,用欧几里得算法求最大公约数化简。

最后输出结果的时候要注意判断一下。

详情见代码


Java Code:

package go.jacob.day822;import java.util.Scanner;public class Demo1 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();String[] strs = new String[n];//三个数分别为分子,分母,带分数的整数部分int numerator = 0, denominator = 0, first = 0;for (int i = 0; i < n; i++)strs[i] = sc.next();sc.close();for (int i = 0; i < n; i++) {int flag = 1, begin = 0;if (strs[i].charAt(0) == '-') {flag = -1;begin = 1;}int tmpNumerator = flag * Integer.parseInt(strs[i].substring(begin, strs[i].indexOf("/")));int tmpDenominator = Integer.parseInt(strs[i].substring(strs[i].indexOf("/") + 1));if (tmpDenominator == 0)return;if (i == 0) {numerator = tmpNumerator;denominator = tmpDenominator;} else {numerator = numerator * tmpDenominator + tmpNumerator * denominator;denominator *= tmpDenominator;}// 使用欧几里得算法求最大公约数,每次计算都要对分数进行化简,放置溢出int factor = gcd(numerator, denominator);if (factor == 0) {System.out.println(0);return;}numerator /= factor;denominator /= factor;}// 把假分数化成带分数first += numerator / denominator;numerator = numerator % denominator;// 输出结果的时候要判断:整数部分是否为0?分子书否为0?if (first != 0)if (numerator != 0)System.out.println(first + " " + numerator + "/" + denominator);elseSystem.out.println(first);else if (numerator != 0)System.out.println(numerator + "/" + denominator);elseSystem.out.println(0);}private static int gcd(int a, int b) {if (a == 0)return 0;if (a < 0)a = -a;if (b < 0)b = -b;if (a < b) {int tmp = a;a = b;b = tmp;}if (a % b == 0)return b;elsereturn gcd(b, a % b);}}






原创粉丝点击