PAT 甲级刷题记录 1001

68 阅读1分钟

题目链接

1001 A+B

思路

分情况讨论

  • 若结果是0

直接输出即可

  • 若结果是正数

则将每一位放到容器里面,遍历容器,若索引%3==0则输出逗号即可。再输出数字

  • 若结果是负数

先输出负号,再乘上-1,转入结果是正数的逻辑即可

小波折

写代码的时候,忘记了Integer的范围了,直接上Long,后来搜了一下Integer的范围是109<=x<=109-10^{9}<=x<=10^{9}忘记了

代码

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        Long a = s.nextLong();
        Long b =s.nextLong();
        Long c = a+b;
        Stack<Long> list = new Stack<>();
        if(c==0)
            System.out.println(0);
        else if(c<0)
        {
            System.out.print("-");
            c*=-1;
        }
        while (c!=0){
            list.add(c%10);
            c/=10;
        }
        // -1000000 0
        for(int i=list.size()-1;i>=0;i--){
            System.out.print(list.pop());
            if(i!=0 && i %3==0)
                System.out.print(',');
            //1234
        }
        s.close();
    }
}