Problem Description
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 − 1 0 6 ≤ a , b ≤ 1 0 6 −10^6 ≤a,b≤10^6 −106≤a,b≤106 . 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实现)
import java.util.Scanner;
/**
* @author snowflake
* @create-date 2019-07-17 23:19
*/
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int sum = cin.nextInt() + cin.nextInt();
// 取出符号位
String sign = sum < 0 ? "-" : "";
// 将数字转化为绝对值
sum = Math.abs(sum);
// 三位数及其一下
if (sum < 1000) {
System.out.println(sign + sum);
} else {
// 将数字转化为字符串
String str = sum + "";
StringBuilder result = new StringBuilder();
// 从右往左进行操作,每次移动三位
for (int i = 0; i < str.length(); i += 3) {
// 如果剩余的字符串还剩余三位以上
if (i + 3 < str.length()) {
result.insert(0, ",").insert(0, str.substring(str.length() - i - 3, str.length() - i));
} else {
result.insert(0, ",").insert(0, str.substring(0, str.length() - i));
}
}
// 结果要补上符号位
System.out.println(sign + result.substring(0, result.length() - 1));
}
}
}