PAT甲级 1001

本文详细解析了PAT甲级1001题目A+BFormat的要求,即两个整数相加并以三位为一组逗号分隔的格式输出结果。提供了旧版和新版代码实现,新版代码简洁高效,使用C++标准库函数完成任务。

题目 A+B Format

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.

解析

两个整数相加,结果以三位为一组逗号分隔

源码

https://github.com/vlluvia/pat

代码


旧代码

#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;


void pat1001(){
    int a,b;
    int i=0;
    char res[10][5]={""};
    cin>>a>>b;
    int re = a+b;
    if (re<0){
        strcat(res[i],"-");
        ++i;
        re = abs(re);
    }
    while(re/1000>0){
        char r[4] ="";
        char t[4]=",";
        char l[4] = "";
        if ((re%1000)/100 == 0){
            strcat(l,"0");
            if ((re%100)/10 == 0){
                strcat(l,"0");
                if ((re%10) == 0){
                    strcat(l,"0");
                }else{
                    snprintf(r, sizeof(r), "%d", re%1000);
                }
            }else{
                snprintf(r, sizeof(r), "%d", re%1000);
            }
        } else{
            snprintf(r, sizeof(r), "%d", re%1000);
        }
        strcat(l,r);
        strcat(t,l);
        strcat(res[i],t);
        re/=1000;
        ++i;
    }
    char r[4] = "";
    snprintf(r, sizeof(r), "%d", re);
    strcat(res[i],r);
    ++i;

    char o[15]="";
    if (a+b<0) {
        strcat(o, res[0]);
        for (int j = i-1; j > 0; --j) {
            strcat(o, res[j]);
        }
    } else{
        for (int j = i-1; j >= 0; --j) {
            strcat(o, res[j]);
        }
    }
    cout<<o<<endl;
}
int main() {
    pat1001();
    return 0;
}

新代码

#include<bits/stdc++.h>

#define INF 1<<30
using namespace std;

void pat1001() {
    long a, b;
    cin >> a >> b;
    long c = a + b;
    if (c > -1000 && c < 1000) {
        cout << c << endl;
    } else if (c > -1000000 && c < 1000000) {
        printf("%d,%03d", c / 1000, abs(c % 1000));
    } else {
        printf("%d,%03d,%03d", c / 1000000, abs(c % 1000000 / 1000), abs(c % 1000));
    }
}

int main() {
    pat1001();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值