ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

1120 Friend Numbers (20 分)——C/C++(set用法)

2021-03-07 19:30:36  阅读:184  来源: 互联网

标签:set 20 temp 1120 sum int line friend


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

题目大意:

给定n个数字,并把每位数字相加的和按从小到大的顺序输出,重复的输出一个。

分析及思路:

使用set集合,set会自动把集合中的数据从小到大排列,并且不会有重复数字。但set中能用迭代器遍历,这样最后一个空格会非常不好掌握,可用数组中转一下。

AC代码:

#include<iostream>
#include<set>
using namespace std;

int a[10010];

int main(){
	int n, i = 0;
	cin >> n;
	set<int> ss;
	for(int i = 0; i < n; i++){
		int temp, sum = 0;
		cin >> temp;
		while(temp > 0){
			sum += temp % 10;
			temp /= 10; 
		}
		ss.insert(sum);
	}
	cout << ss.size() << endl;
	set<int>::iterator it;              
    for(it = ss.begin(); it != ss.end(); it++) a[i++] = *it;
    for(i = 0; i < ss.size() - 1; i++) cout << a[i] << ' ';
    cout << a[i] << endl;
	return 0;
}

标签:set,20,temp,1120,sum,int,line,friend
来源: https://blog.csdn.net/qq_47733361/article/details/114492484

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有