PTA甲级 1001 A+B Format PAT (Advanced Level) Practice

coding复健之路之PAT甲级,从柳神那里学了很多,代码清晰可读性强,思路也可以细品,前辈的代码真好www然后建议按题目分类做,而不是按题库顺序做。

柳婼的博客

柳神(柳婼)PAT甲级题目链接

【置顶】【PAT】PAT甲级题目及分类总结(持续更新ing)

在这里插入图片描述

一、题目描述

原题链接 1001 A+B

类型:简单模拟

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 − 1 0 6 ≤ a , b ≤ 1 0 6 −10^6 ≤a,b≤10^6 106a,b106 . The numbers are separated by a space.

扫描二维码关注公众号,回复: 14636557 查看本文章

三、输出

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.

四、样例

输入:

-1000000 9

输出:

-999,991

代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB

五、思路和代码

就是简单的两数相加 + 考虑负数 + 格式化输出。

格式化输出:从右到左每 3 位输出【,】,当前位的下标i满足**(i+1)%3==len%3**并且i不是最后一位。

#include <iostream>
using namespace std;
int main(){
    
    
    int a, b;
    cin >> a >> b;
    string res = to_string(a+b);
    int len = res.length();
    for(int i = 0; i < len; i++){
    
    
        cout << res[i];
        if(res[i] == '-') continue;
        if((i+1) % 3 == len % 3 && i != len-1) cout << ",";
    }
    return 0;
} 


除了c++,java自带了格式化输出,但是耗时emmm

import java.util.Scanner;

public class Main{
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        int a = input.nextInt();
        int b = input.nextInt();
        System.out.printf("%,d", a+b);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45722196/article/details/127663933