PAT (Advanced Level) Practice No.1001

Question

001 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 −10​6​​≤a,b≤10​6​​. 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

Solution

import java.util.LinkedList;
import java.util.Scanner;

//CreateTime: 2019/3/21 23:21
//Author:     月小水长(https://github.com/inspurer)
/*
    类名:首字母大写,其他单词中首字母大写,其他小写
    方法名:首字母小写,其他单词中首字母大写,其他小写
    变量:与方法名规则同
    包名:全部小写
*/
public class Main {
    public static void main(String [] args){
        Scanner scanner = new Scanner(System.in);
        int num1 = Integer.parseInt(scanner.next());
        int num2 = Integer.parseInt(scanner.next());
        scanner.close();
        num1 += num2;
        int flag = num1>=0?1:0;
        num1 = num1>0?num1:-num1;
        if(String.valueOf(num1).length()<4) {
            if (flag == 0) {
                System.out.print(-num1);
            } else {
                System.out.print(num1);
            }
            return;
        }
        LinkedList<String> result = new LinkedList<String>();
        do{
            result.add(String.valueOf(num1%10));
            num1 /= 10;
            if((result.size()+1)%4==0&&num1>0){
                result.add(",");
            }
        }while (num1>0);
        if(flag==0){
            result.add("-");
        }
        for(int i = result.size()-1;i>=0;i--)
            System.out.print(result.get(i));
    }
}

Conclusion

Scanner.nextInt() 方法只能接收正整数,如输入负整数则会忽略掉掉负号,相当于对输入取 abs() ,要想解决这个 Bug,可以通过

1
int num1 = Integer.parseInt(scanner.next());

解决。

next() 和 nextLine() 都接收字符串;
next() 方法一定要接收到有效字符串才可以结束输入,对输入有效字符之前遇到的空格键、Tab 键或回车键等,next() 方法会自动将其去掉,只有在输入有效字符之后,next() 方法才将其后输入的空格键、Tab 键或回车键视为分隔符或结束符;
nextLine() 方法的结束符只是回车键,即 nextLine() 方法返回的是回车键的所有字符。

Code

PAT Advanced Pratice 题解系列代码集合

本文标题:PAT (Advanced Level) Practice No.1001

文章作者:月小水长

发布时间:2019年03月22日 - 23:03

最后更新:2019年03月22日 - 23:03

原始链接:https://inspurer.github.io/2019/03/22/PAT-Advanced-Level-Practice-No-1001/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

您的赞助将鼓励我继续创作!
-------------本文结束感谢阅读-------------