PTA(A)1120 Friend Numbers (20分)
程序员文章站
2022-07-08 22:19:48
...
Sample Input
8
123 899 51 998 27 33 36 12
Sample Output
4
3 6 9 26
思路: 输入同时记录数字各位的总和,添加到一个vector里,最后排序输出即可,注意重复判断。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
vector<int>vec;
int a[10002];
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
{
int x;
int ans = 0;
scanf("%d", &x);
while (x != 0)
{
ans += (x % 10);
x /= 10;
}
if (!a[ans])
{
a[ans] = 1;
vec.push_back(ans);
}
}
sort(vec.begin(), vec.end());
printf("%d\n", vec.size());
for (int i = 0; i < vec.size(); ++i)
i == 0 ? printf("%d", vec[i]) : printf(" %d", vec[i]);
//getchar(); getchar();
return 0;
}