PAT|1120 Friend Numbers(哈希排序、字符串)

题目大意

如果两个整数共享相同的数字总和,则称为“朋友号码”,该总和就是他们的“朋友 ID”。例如,123 和 51 是朋友编号,因为 1+2+3 = 5+1 = 6,而 6 是他们的朋友 ID。给定一些数字,您应该计算其中不同朋友 ID 的数量。

解题思路

  • 首先根据题意了解定义,是指的每一位的数字加和
  • 使用map可以在防止重复的同时排序

代码

#include<bits/stdc++.h>
using namespace std;
map<int, int> res;
int sumString(int x) {
	int ans = 0;
	while (x) {
		ans += x % 10;
		x = x / 10;
	}
	return ans;	
}
int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		int tem;
		cin >> tem;
		int sum = sumString(tem);
		if (res.find(sum) == res.end()) {
			res.emplace(sum, 1);
		}
	}
	if (res.size() == 0) {
		cout << 0 << endl;
	}
	else {
		cout << res.size() << endl;
		map<int, int>::iterator iter = res.begin();
		cout << iter->first;
		iter++;
		while (iter != res.end()) {
			cout << ' ' << iter->first;
			iter++;
		}
		cout << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值