首页 > 试题广场 >

A+B Format (20)

[编程题]A+B Format (20)
  • 热度指数:3949 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
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.
示例1

输入

-1000000 9

输出

-999,991
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
            String[] input = br.readLine().split(" ");
            int sum = Integer.parseInt(input[0]) + Integer.parseInt(input[1]);
            if (Math.abs(sum) < 1000) {
                System.out.println(sum);
            } else {
                if (sum < 0) {
                    System.out.print('-');
                }
                sum = Math.abs(sum);
                ArrayList<Integer> list = new ArrayList<>();
                while (sum > 0) {
                    list.add(sum % 1000);
                    sum /= 1000;
                }
                int groups = list.size();
                System.out.print(list.get(groups - 1));
                for (int i = groups - 2; i >= 0; --i) {
                    System.out.print(",");
                    String num = String.valueOf(list.get(i));
                    for (int j = 0; j <    3 - num.length(); ++j) {
                        System.out.print(0);
                    }
                    System.out.print(num);
                }
                System.out.println();
            }
        } catch (IOException ie){}
    }
}
发表于 2025-02-05 23:02:10 回复(0)