[PAT] 1081 Rational Sum (20 分)Java
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[PAT] 1081 Rational Sum (20 分)Java,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2519字,纯文字阅读大概需要4分钟。
内容图文
![[PAT] 1081 Rational Sum (20 分)Java](/upload/InfoBanner/zyjiaocheng/838/d0ffd640dc7b4f1394d38dccccc8c674.jpg)
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:
5
2/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
Sample Input 3:
3
1/3 -1/6 1/8
Sample Output 3:
7/24
1 package pattest; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 /** 8 * @Auther: Xingzheng Wang 9 * @Date: 2019/2/26 21:26 10 * @Description: pattest 11 * @Version: 1.0 12 */ 13 public class PAT1081 { 14 public static void main(String[] args) throws IOException { 15 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 16 String n = reader.readLine(); 17 String[] s1 = reader.readLine().split(" "); 18 String[] s2 = s1[0].split("/"); 19 int a = Integer.parseInt(s2[0]), b = Integer.parseInt(s2[1]), sum = 0; 20 for (int i = 1; i < Integer.parseInt(n); i++) { 21 String[] s = s1[i].split("/"); 22 int atemp = Integer.parseInt(s[0]); 23 int btemp = Integer.parseInt(s[1]); 24 a = a * btemp + atemp * b; 25 b = b * btemp; 26 int c = GCD(a, b); 27 a = a / c; 28 b = b / c; 29 } 30 if (a % b == 0) { 31 System.out.print(a / b); 32 } else { 33 if (Math.abs(a) > Math.abs(b)) { 34 if (a > 0) { 35 System.out.printf("%d %d/%d", a / b, a - a / b * b, b); 36 } else { 37 a = -a; 38 System.out.printf("-%d %d/%d", a / b, a - a / b * b, b); 39 } 40 } else { 41 System.out.printf("%d/%d", a - a / b * b, b); 42 } 43 } 44 } 45 46 private static int GCD(int m, int n) { 47 return n == 0 ? m : GCD(n, m % n); 48 } 49 }
内容总结
以上是互联网集市为您收集整理的[PAT] 1081 Rational Sum (20 分)Java全部内容,希望文章能够帮你解决[PAT] 1081 Rational Sum (20 分)Java所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。