PAT B1064 朋友数 (20分)

题目链接https://pintia.cn/problem-sets/994805260223102976/problems/994805267416334336

题目描述
如果两个整数各位数字的和是一样的,则被称为是“朋友数”,而那个公共的和就是它们的“朋友证号”。例如 123 和 51 就是朋友数,因为 1+2+3 = 5+1 = 6,而 6 就是它们的朋友证号。给定一些整数,要求你统计一下它们中有多少个不同的朋友证号。

输入
输入第一行给出正整数 N。随后一行给出 N 个正整数,数字间以空格分隔。题目保证所有数字小于 10^​4​​ 。

输出
首先第一行输出给定数字中不同的朋友证号的个数;随后一行按递增顺序输出这些朋友证号,数字间隔一个空格,且行末不得有多余空格。

样例输入
8
123 899 51 998 27 33 36 12

样例输出
4
3 6 9 26

代码

#include <cstdio>
#include <set>
#include <algorithm>
using namespace std;


int main() {
	set<int> t;
	int n, a, sum;
	scanf("%d", &n);
	for(int i = 0; i < n; i++) {
		scanf("%d", &a);
		sum = 0;					//每次清零
		while(a > 0) {
			sum += (a % 10);
			a /= 10;
		}
		t.insert(sum);
	}
	printf("%d\n", t.size());
	for(set<int>::iterator it = t.begin(); it != t.end(); it++) {
		if(it != t.begin())
			printf(" ");
		printf("%d", *it);
	}
	return 0;

}
发布了327 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Rhao999/article/details/105151940