PAT (Advanced Level) Practise 1001 解题报告


GiHub
markdown PDF


问题描述

A+B Format (20)
时间限制 400 ms
内存限制 65536 kB
代码长度限制 16000 B
判题程序 Standard
作者 CHEN, Yue
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)。


解题思路

题目中a,b的数据范围都比较小,所以使用了效率较低,但代码量少的做法

  1. 计算a+b,并转换为字符串;
  2. 检验是否带有负号;
  3. 逐位输出字符,在满足条件:剩余字符数为3的倍数 的位置输出分隔符。

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
	int i,j,k,n,m,s,t,a,b;
	char c[10];
	cin>>a>>b;
	s=a+b;
	if (s<0) sprintf(c,"%d",-s);
	else sprintf(c,"%d",s);
	if (s<0) cout<<"-";
	n=strlen(c);
	for (i=0;i<n;i++)
	{
		cout<<c[i];
		if (((n-i-1)%3==0)&&(i<n-1)) cout<<",";
	}
	return 0;
}

提交记录

此处输入图片的描述


之后会继续更新自查后的代码。。

posted @ 2017-01-21 17:42  Eventide  阅读(285)  评论(2编辑  收藏  举报