【PAT甲级 - C++题解】1120 Friend Numbers

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1120 Friend Numbers (pintia.cn)
🔑中文翻译:朋友数
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1120 Friend Numbers

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

Sample Output:

4
3 6 9 26
题意

这道题不要混淆了题目条件,题目需要求的是有多少朋友证号,而朋友证号是指每个数的各位之和,比如 123 的朋友证号是 1 + 2 + 3 = 633 的朋友证号也是 3 + 3 = 6 ,并且 12333 被称为朋友数。但是需要注意的是,并不是说只有被称为朋友数才能被称为朋友证号,所以这道题朋友数这个性质实际上用不到。

思路

根据上述题意可以知道我们需要找出有多少个不同的朋友证号,可以利用 set 容器的性质,会帮我们自动过滤掉重复的值,并且为我们自动排序好。所以只需要将每个数的朋友证号计算出来再放进 set 中,最后输出即可。

代码
#include<bits/stdc++.h>
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值