[Java] 1001. A+B Format (20)-PAT甲级

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
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
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

题目大意:计算A+B的和,然后以每三位加一个","的格式输出。

PS:感谢github用户@fs19910227提供的pull request~

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] split = reader.readLine().split(" ");
        Integer x = Integer.valueOf(split[0]) + Integer.valueOf(split[1]);
        char[] chars = x.toString().toCharArray();
        int modOffset = chars.length % 3;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '-') {
                System.out.print('-');
                continue;
            }
            System.out.print(chars[i] - 48);
            if (i == chars.length - 1) {
                System.out.println();
            } else if ((i + 1) % 3 == modOffset) {
                System.out.print(',');
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/liuchuo/article/details/81436096