PAT 1001.A+B Format

原题地址: http://www.patest.cn/contests/pat-a-practise/1001
1001. A+B Format (20)

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

本题

package com.dye.pat.t1001;

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String[] input = in.nextLine().split(" ");
        in.close();

        int a = Integer.parseInt(input[0].trim());
        int b = Integer.parseInt(input[1].trim());

        String result = "" + (a + b);
        String flag = "";


        if (result.charAt(0) == '-') {
            flag = "-";
            result = result.substring(1);
        }

        int count = result.length();
        count = (3 - count % 3) % 3;

        for (int i = 0; i < result.length(); i++) {

            if (count !=0 &&count % 3 == 0)
                flag = flag + ",";
            flag += result.substring(i, i+1);
            count++;
        }
        System.out.println(flag);
    }
}

你可能感兴趣的:(PAT)