PAT - 1001 A+B Format (20)

本篇介绍了一个简单的程序设计问题,即计算两个整数的和,并将结果以标准格式输出,包括如何处理正负号及千位分隔符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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


题目大意:计算 a 和 b 的和并用标准格式输出,即数字必须用逗号分成三组(除非少于四位数)。

数据范围:-1000000 <= a, b <= 1000000

解题思路:数据范围比较小,开 int 就可以了。如果小于四位数直接输出。否则:先记录和的符号,对 10 取余把个位提取出来 +’0’ 转成字符存入字符数组,每三位加入一个逗号,最后逆序输出。


#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100+10;
const int INF = 0x3f3f3f3f;
int main() {
    int a, b;
    scanf("%d%d", &a, &b);
    int c = a + b;
    if (c < 1000 && c > -1000) printf("%d\n", c);
    else {
        int op = c >= 0 ? 1 : 0;
        c = c > 0 ? c : -c;
        int t = 0, cnt = 0;
        char tmp[15];
        while (c) {
            if (cnt%3 == 0) {
                tmp[t++] = ',';
                cnt = 0;
            }
            tmp[t++] = (c % 10) + '0';
            c /= 10;
            cnt++;
        }
        if (!op) cout << "-";
        for (int i = t-1; i > 0; i--) {
            printf("%c", tmp[i]);
        }
        printf("\n");
    }

    return 0;
}

提交时间状态分数题目编译器耗时
2018/7/5 22:02:53答案正确201001C++ (g++)3 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值