我是靠谱客的博主 认真花卷,这篇文章主要介绍[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(',');
            }
        }
    }
}

 

最后

以上就是认真花卷最近收集整理的关于[Java] 1001. A+B Format (20)-PAT甲级的全部内容,更多相关[Java]内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(140)

评论列表共有 0 条评论

立即
投稿
返回
顶部