[PAT A1001]A+B Format

[PAT A1001]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).

输入格式

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.

输出格式

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.

输入样例

-1000000 9

输出样例

-999,991

解析

  1. 题目解释,输入两个数a,b,然后计算他们的和并以标准形式输出,就是按照从低到高每三位加一个逗号输出
  2. 根据题目给出的数的范围,我们可以使用两个int类型的变量去存储他们,而且保证不会溢出,具体实现过程见代码和注释
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
 int a, b;
 string str, ans;
 cin >> a >> b;
 a = a + b;
 str = to_string(a);  //数字转化为字符串
 reverse(str.begin(), str.end());  //转置这个字符串
 for (int i = 0; i < str.length(); i++) {
  ans += str[i];
  if ((i % 3 == 2) && (i + 1 < str.length()) && (str[i + 1] != '-')) ans += ','; 
  //如果某个地方该加逗号,我们必须判断它的下一位是不是超过了长度,以及它的下一位是不是‘-’号,这两种情况我们是不能加的
 }
 reverse(ans.begin(), ans.end());  //变回原来的格式
 cout << ans;
 return 0;
}
水平有限,如果代码有任何问题或者有不明白的地方,欢迎在留言区评论;也欢迎各位提出宝贵的意见!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值