PAT 1001 A+B Format

 

Sample Input:

-1000000 9
 

Sample Output:

-999,991

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main()
{
	int a, b;
	cin >> a >> b;
	int sum = a + b;
	if (sum < 0) {
		cout << '-' ;
		sum = abs(sum);
	}
	char s[20];
	sprintf(s,"%d",sum);
	int len = strlen(s);
	if (len <= 3) {
		cout << s << endl;
	}
	else {
		int pos = 0;
		int k = len % 3 == 0 ? 3 : len % 3;
		for ( pos = 0; pos < k; pos++) {
			cout << s[pos];
		}
		for (; pos < len; pos += 3) {
			cout << ',';
			cout << s[pos] << s[pos + 1] << s[pos + 2];
		}
	}
	return 0;
}
 
1.负数先输出符号,然后取绝对值
2.先把前n%3个高位输出,注意,当n%3=0的时候,并不是不用输出,而是要把前3位输出!当n%3=1或者2的时候,就输出前1或者2位
后面剩下的位数必定是3的倍数,遍历输出就行了
posted @ 2020-08-15 17:14  houyz  阅读(74)  评论(0)    收藏  举报