PAT 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 Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −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

题目大意:

给你两个数字,直接相加。 把相加后的数组按照 从右到左,每三位添加一个逗号。如果正好数到结果的开头,这个头号不用添加。 就跟咱们常见的一些比较大的数字 用逗号分开方便阅读一样。

思路分析:

不知道你们的第一反应是什么,我第一反应就是把相加的结果 倒过来,把逗号插进入,然后在把插入逗号的结果倒置回来。直接输出结果。

首先这个符号位和我们的逗号是没有关系的。因此符号位如果是- 单独输出, 整数没有符号位。然后我们从有向左,每隔三个数字插入一个 逗号。 如果当前插入这个逗号的位置正好是 数字的最开端。那么这个插入取消。

完整代码:

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

public class P1001 {
     
    public static void main(String[] args) throws IOException {
     
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String[] data = bf.readLine().split(" ");
        int A = Integer.parseInt(data[0]);
        int B = Integer.parseInt(data[1]);
        String s = "" + Math.abs(A+B); // 将A+B转成字符串
        String res = change(s) ;
        if(A+B <0)
            System.out.print("-");
        System.out.print(res);

    }

    // 符号不要管 从右向左处理
    static  String change(String s) {
     
        StringBuilder stringBuilder = new StringBuilder();
        int length = s.length();
        for (int i = 1; i <= length; i++) {
      //从左向右进行处理 每隔3位添加一个逗号
            stringBuilder.append(s.charAt(length - i));
            if (i % 3 == 0 && i!=length) //当i==length 那么 length-i==0 也就是到了开头 这个不用添加
                stringBuilder.append(",");
        }

        return stringBuilder.reverse().toString();//由于是逆序添加,因此还要翻转回去
    }
}

你可能感兴趣的:(PAT,算法)