1001. A+B Format (20)

本文介绍了一种解决A+B Format问题的方法,该问题要求计算两个整数的和,并以特定格式输出。通过使用栈来分组存储结果,并在输出时进行格式调整,确保了输出的正确性。

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

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

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

分析:首先将和按3位分开,自然想到了对1000取余的办法。于是按照二进制的除二取余的思路将和分开。需要注意的是,对1000取余后得到的结果可能不是三位数,而是两位或者一位,这个时候就需要在输出的时候在前面补零凑够三位。这里用到了栈。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;

int main()
{
    long a,b,c;
    cin>>a>>b;
    c=a+b;
    if(c==0)
    {
        cout<<0<<endl;
        return 0;
    }
    int flag=1;
    if(c<0)
    {
        c*=-1;
        flag=-1;
    }
    stack<long> ans;
    while(c>0)
    {
        ans.push(c%1000);
        c/=1000;
    }
    if(flag==-1)
    {
        printf("-");
    }
    //输出第一个数
    printf("%ld", ans.top());
    ans.pop();
    while(ans.size()>0)
    {
        printf(",%03ld",ans.top());
        ans.pop();
    }
    cout<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/xiongmao-cpp/p/6385926.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值