您的位置:首页 > 其它

PAT甲级1001. A+B Format (20)

2017-08-24 10:56 483 查看

题目链接

https://www.patest.cn/contests/pat-a-practise/1001

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

思路分析

1.也就是输入两个数a和b,把a+b的和按照银行标准输出出来,每三位输出一个逗号

2.考虑特殊情况比如 a+b = 0可以直接输出

3.把a+b和放在字符数组中,判断下标j满足条件输出逗号

代码

#include<iostream>
using namespace std;

int main()
{
int a,b;
int c[100000];//用来倒序保存sum的每一位
cin>>a>>b;
int sum = a+b;
int t = 1;
if(sum < 0)
t = -1;
int i = 1;
int k = t*sum;//保证sum绝对值为正
while(k)//倒序保存sum
{
c[i] = k%10 ;
i++;
k = k/10;
}//此时sum一共有i-1位
if(sum < 0)//sum < 0 先输出-号
cout<<"-";
if(sum == 0) //考虑特殊情况 这也是一个测试点 一开始这个情况没考虑到
cout<<sum;
for(int j = i-1 ;j >= 1;j--)
{
if(j%3 == 0 && j!=i-1)//判断条件,当j为3的倍数且j不是i-1(第1位)输出,
cout<<",";
cout<<c[j];
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: