Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1001. A+B Format

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

AC code

#include <cstdio>
#include <cstring>

int main ()
{
	int a, b;
	scanf("%d%d", &a, &b);
	a += b;

	if (a < 0)
		printf("-"), a = -a;

	char s[20];
	sprintf(s, "%d", a);

	for (int i = 0, len = strlen(s); s[i]; i++)
	{
		if ((len-i) % 3 == 0 && i) printf(",");
		printf("%c", s[i]);
	}
	printf("\n");

	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论