【PAT】A1120 Friend Numbers (20point(s))


Author: CHEN, Yue
Organization: 浙江大学
Time Limit: 400 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB

A1120 Friend Numbers (20point(s))

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 10^​4​​.

Output Specification:

For each case, print in the first line the number of different frind 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

Code

#include <stdio.h>
#include <iostream>
#include <set>
using namespace std;
set<int> res;
int main(){
    int n,temp;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&temp);
        int sum=0;
        while(temp!=0){
            sum+=temp%10;
            temp/=10;
        }
        res.insert(sum);
    }
    printf("%d\n",res.size());
    for(set<int>::iterator it=res.begin();it!=res.end();it++){
        if(it==res.begin()) printf("%d",*it);
        else    printf(" %d",*it);
    }
}

Analysis

-位数和一直相加,直至成为一个个位数,称为朋友ID。如果若干个数进行以上操作后得到的ID相同,则他们互相是朋友数。

-给出一串数字,求这些数字不同的朋友ID数并输出,并且求这些数不同的朋友ID,结果按照增序输出。

-使用一个set容器存储每一个数的朋友ID。最后set中的内容就是按增序排列的结果。

发布了159 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ztmajor/article/details/104036387