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

 算法:

  1. 算法开始。
  2. 读入a,b。
  3. 计算a+b。
  4. 使用sprintf()函数将和写入字符串string。
  5. 使用strlen计算字符串长度,赋值给n。
  6. 如果和大于等于零,继续,否则跳到第十一步。
  7. 如果i不小于n,则跳到第十五步。
  8. 输出string[i]。
  9. 如果(n-i)%3==1而且n-i!=1,输出逗号。
  10. i++,回到第七步。
  11. 如果i不小于n,则跳到第十五步。
  12. 输出string[i]。
  13. 如果(n-i)%3==1而且n-i!=1而且i!=0,输出逗号。
  14. i++,回到第十一步。
  15. 算法结束。
算法时间复杂度O(1),空间复杂度O(1)。其实可以把第六步的判断整合到第九步的判断里,然后把第七步到第十步和第十一步到第十四步的两个循环合并成一个循环。这样可以减少代码的复杂度,但是会增加判断的次数。
下列代码编写于VS2015,修改sprintf_s()、scanf_s()函数就可以在PAT上AC。
#include <stdio.h>
#include <string.h>
#define MAX 20
int main(void) {
	int a, b, sum, i, length;
	char array[MAX];
	scanf_s("%d %d", &a, &b);
	sum = a + b;
	sprintf_s(array, MAX, "%d", sum);
	length = strlen(array);
	if (sum >= 0) {
		for (i = 0; i < length; i++) {
			putchar(array[i]);
			if ((length - i) % 3 == 1 && length - i != 1) {
				putchar(',');
			}
		}
	}
	else {
		for (i = 0; i < length; i++) {
			putchar(array[i]);
			if ((length - i) % 3 == 1 && length - i != 1 && i != 0) {
				putchar(',');
			}
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值