PAT Advanced Level 1001 A+B Format

PAT Advanced Level 1001 A+B Format

1001 A+B Format

题目原文

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

分析

题目要求将A+B的结果按从右起每隔三位插入一个小数点输出。
故可以先算出A+B的结果,然后再考虑如何分割。
分割的方法可以是:

  1. 先转化为字符串对象,再每隔三位插入一个逗号;
  2. 用数组存储每三位组成的数字,再在输出时做文章。
    第一种方法要注意指针的位置(在哪里插入逗号等),第二种方法要注意填充0以组成三位数字。
    这里提供第二种方法的代码。

AC代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
    int a, b; //定义输入数a,b
    cin >> a >> b;
    int ans = a + b; //计算a+b
    if (ans == 0)
        cout << 0;
    else
    {
        vector<int> *v = new vector<int>(); //用vector模拟链表,每次取得的末三位插入到第一位以保证顺序
        while (ans != 0)
        { //每次提取ans的末3位,并直接十进制右移3位。
            v->insert(v->begin(), ans % 1000);
            ans /= 1000;
        }
        auto i = v->begin();
        cout << *i;
        i++;
        for (; i != v->end(); i++)
        {
            cout << "," << setw(3) << setfill('0') << abs(*i);
        }
        delete v;
    }
    cout << endl;
    return 0;
}

同思路下也可以用栈stack来替代vector处理数据,思路基本相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值