• 【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
    
    • 1
    • 2

    Sample Output:

    4
    3 6 9 26
    
    • 1
    • 2
    题意

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

    思路

    根据上述题意可以知道我们需要找出有多少个不同的朋友证号,可以利用 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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    可以帮我做一下吗?研究很久还是不会画实体类图
    ubuntu20.04中安装配置docker nvidia容器来实现宿主机GPU的调用
    JAVA赋值不使用引用的办法
    过去10年的10起重大网络安全事件
    mulesoft Module 6 quiz 解析
    第P6周—好莱坞明星识别(1)
    Virtualbox固定存储硬盘转换为动态存储硬盘
    使用pymodbus进行modbus-TCP通信
    We have awesome remote U.S. jobs waiting for engineers like you.
    pytorch-12 深度学习基础网络的数据集创建及手动搭建实现
  • 原文地址:https://blog.csdn.net/Newin2020/article/details/127823562