题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400
Question:
Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −1000000 ≤a,b≤1000000. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
1000000 9
Sample Output:
-999,991
我的代码是用Java写的,因为最近另一个比赛是用Java报的。
思路:int类型的总和转化为String,然后利用StringBuffer的反转函数reverse(),进行颠倒转化,在这过程中,添加逗号“,”。最后将StringBuffer转化为String,输出结果。
import java.util.Scanner;
public class P1001 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;
String str = String.valueOf(sum);
if((str.length()<=3&&sum>0)||(str.length()<=4&&sum<0)||sum == 0)
System.out.println(str);
else {
if(sum<0) {
int time = 0;
for(int i = str.length()-1;i>=1;i--) {
if(time%3==0&&time>0)
sb.append(',');
sb.append(str.charAt(i));
time ++;
}
System.out.println("-"+sb.reverse().toString());
}
else {
int time = 0;
for(int i = str.length()-1;i>=0;i--) {
if(time%3==0&&time>0)
sb.append(',');
sb.append(str.charAt(i));
time ++;
}
System.out.println(sb.reverse().toString());
}
}
}
}
最后测试案例全过了,测试结果如下: