PAT (Advanced Level) Practice 1001 A B Format (20 分)

时间:2022-07-26
本文章向大家介绍PAT (Advanced Level) Practice 1001 A B Format (20 分),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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 −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

甲级第一题!自然要讲的清楚~

看要求,很简单计算两数之和,不就是相加吗,噢,原来是从个位开始,每隔三位加一个逗号,到最后不满三位则不加,先考虑简单的事情,如果是负数先输出负号,然后反向存数位,遇到下标是三的倍数就输出逗号(英文),注意最后一个逗号不输出~

// luogu-judger-enable-o2
#include<bits/stdc++.h>
#include<unordered_set>
#define rg register ll
#define inf 2147483647
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
#define ll long long
#define maxn 300005
#define lb(x) (x&(-x))
const double eps = 1e-6;
using namespace std;
inline ll read()
{
	char ch = getchar(); ll s = 0, w = 1;
	while (ch < 48 || ch>57) { if (ch == '-')w = -1; ch = getchar(); }
	while (ch >= 48 && ch <= 57) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	return s * w;
}
inline void write(ll x)
{
	if (x < 0)putchar('-'), x = -x;
	if (x > 9)write(x / 10);
	putchar(x % 10 + 48);
}
ll a,b,tot=-1;
char s[500];
int main()
{
    cin>>a>>b;
    ll c=a+b;
    if(c==0)
    {
        cout<<0<<endl;
        return 0;
    }
    if(c<0)
    {
        cout<<"-";
    }
    c=abs(c);
    //cout<<c<<endl;
    while(c)
    {
        s[++tot]=c%10+48;
        //cout<<s[tot]<<endl;
        c/=10;
    }
    //cout<<s<<endl;
    for(rg i=tot;i>=0;i--)
    {
        cout<<s[i];
        if(i%3==0&&i)cout<<',';
    }
    return 0;
}