先上代码:
import java.util.*;
import java.math.*;
public class Main {
private static long gcd(long nfz, long nfm) {
long a = Math.min(nfz, nfm);
long b = Math.max(nfz, nfm);
if (b % a == 0) {
return a;
}
return gcd(a, b % a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
String[] ori = sc.nextLine().split(" ");
String resInt = "";
long resZi = 1, resMu = 1;
//相加的过程
for (int i = 0; i < num; i++) {
String[] single = ori[i].split("/");
if (i == 0) {
resZi = Long.parseLong(single[0]);
resMu = Long.parseLong(single[1]);
continue;
}
long newZi = Long.parseLong(single[0]), newMu = Long.parseLong(single[1]);
resZi = resZi * newMu + resMu * newZi;
resMu *= newMu;
}
//这里太黑了,对应测试用例第六个
if (resZi == 0) {
System.out.println(0);
return;
}
//如果整数部分不为0
if (resZi / resMu != 0) {
resInt = resZi / resMu+"";
System.out.print(resInt);
}
//除去整除部分
resZi %= resMu;
if (resZi == 0) {
return;
}
//约分
long gg =gcd(Math.abs(resZi), Math.abs(resMu));// 分子为0不需要约分
resZi /= gg;
resMu /= gg;
//打印结果的分数部分
if (!"".equals(resInt)) {
System.out.print(" ");
}
System.out.print(resZi + "/" + resMu);
}
}
聊聊吧,为了通过所有用例,我花了很多时间。
难点:约分、考虑到结果为0的特殊情况、整数部分与分数部分间的空格设置
坑点
:题目说“如果结果的整数部分为0,则只输出分数部分。”那么如果不仅整数部分为0,而是整个结果为0,那怎么表示?题目都没说清楚——答案是,仍然输出整数部分为0。