题目描述:
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).
输入描述:
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.
输出描述:
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.
示例:
输入:
-1000000 9
输出:
-999,991
算法思路:
该题从题目中看,是一道较为简单的题目(送分),首先将输入读取后获得两个计算的数字,计算的结果可以分为负数和非负数,对于这两类结果我们进行分类讨论;因为对于负数来讲,由于其存在负号,那么倘若和负号一起连续出现长度为4,那么这个不能分隔;但对于非负数由于没有负号的存在,那么每三个长度就要隔开。
这里我们可以将整数型的结果先转换成字符串,然后利用Java当中的StringBuffer从字符串的最末尾开始每隔三个长度的数字就加一个“,”,同时注意结果为正负的讨论。
算法实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] str = line.split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
int res = a+b;
String str_res = String.valueOf(res);
StringBuffer str_res2 = new StringBuffer(str_res);
if (res < 0) {
for (int i=str_res2.length()-3;i>1;i-=3){
str_res2.insert(i,',');
}
} else if (res>=0) {
for (int i=str_res2.length()-3;i>0;i-=3){
str_res2.insert(i,',');
}
}
System.out.println(str_res2);
}
}
提交结果: