✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1120 Friend Numbers (pintia.cn)
🔑中文翻译:朋友数
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
Two integers are called “friend numbers” if they share the same sum of their digits, and the sum is their “friend ID”. For example, 123 and 51 are friend numbers since 1+2+3 = 5+1 = 6, and 6 is their friend ID. Given some numbers, you are supposed to count the number of different friend ID’s among them.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N. Then N positive integers are given in the next line, separated by spaces. All the numbers are less than 104.
Output Specification:
For each case, print in the first line the number of different friend ID’s among the given integers. Then in the second line, output the friend ID’s in increasing order. The numbers must be separated by exactly one space and there must be no extra space at the end of the line.
Sample Input:
8 123 899 51 998 27 33 36 12
- 1
- 2
Sample Output:
4 3 6 9 26
- 1
- 2
这道题不要混淆了题目条件,题目需要求的是有多少朋友证号,而朋友证号是指每个数的各位之和,比如 123
的朋友证号是 1 + 2 + 3 = 6
,33
的朋友证号也是 3 + 3 = 6
,并且 123
和 33
被称为朋友数。但是需要注意的是,并不是说只有被称为朋友数才能被称为朋友证号,所以这道题朋友数这个性质实际上用不到。
根据上述题意可以知道我们需要找出有多少个不同的朋友证号,可以利用 set
容器的性质,会帮我们自动过滤掉重复的值,并且为我们自动排序好。所以只需要将每个数的朋友证号计算出来再放进 set
中,最后输出即可。
#include
using namespace std;
int main()
{
int n;
cin >> n;
set<int> nums;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
//计算各位之和
int sum = 0;
while (x) sum += x % 10, x /= 10;
nums.insert(sum); //set容器中已经帮我们过滤掉相同的朋友证号了
}
//输出答案
cout << nums.size() << endl;
bool is_first = true;
for (auto& s : nums)
{
if (is_first) is_first = false;
else cout << " ";
cout << s;
}
cout << endl;
return 0;
}