A1120 Friend Numbers (20 point(s))

数字各位相加

1. 原文

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 frind 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:

1
2
8
123 899 51 998 27 33 36 12

Sample output:

1
2
4
3 6 9 26

2. 解析

数字🔢各位相加:

1
2
3
4
5
6
7
8
9
10
//way 1
do{
sum+=a%10;
a/=10;
}while(a!=0);
//way 2
for (int i = 0; str[i] != '\0'; ++i){
int num=str[i]-'0';
sum+=num;
}

相加和值防重复

set.insert(sum);

3. AC代码

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
#include<cstdio>
#include<set>
using namespace std;
char str[100];
set<int> s;
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
scanf("%s",str);
int sum=0;
for (int i = 0; str[i] != '\0'; ++i)
{
int num=str[i]-'0';
sum+=num;
}
s.insert(sum);
}
printf("%lu\n",s.size());
for (set<int>::iterator i = s.begin(); i != s.end(); ++i)
{
if (i!=s.begin())
{
printf(" ");
}
printf("%d",*i);
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1120/
  • 发布时间: 2019-09-03 08:34
  • 更新时间: 2021-10-29 14:08
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!