1064 朋友数 (20 point(s))

#include <bits/stdc++.h>
using namespace std;

int main() {
	int n, tmp, a, b, c, d, first = 0;
	set<int> fri;
	cin >> n;
	
	while(n--){
		cin >> tmp;
		a = tmp % 10;
		b = tmp / 10 % 10;
		c = tmp / 10 / 10 % 10;
		d = tmp / 10 / 10 / 10; 
		fri.insert(a + b + c + d);
	}
	cout << fri.size() << endl;
	for(auto f: fri) cout << (first++ ? " " : "") << f;
}

这题因为数据比较小“所有数字小于 10^4”,可以直接枚举各个位的数字。高位如果不存在为 0 ,加起来不会影响结果。

当然也可以用辗转相除法得到结果相加。

while (n){
	sum += n % 10;
	n /= 10;
}

参考代码

posted on 2021-09-07 08:12  Atl212  阅读(33)  评论(0)    收藏  举报

导航