Cover image for 面试经典150题 P202 快乐数

面试经典150题 P202 快乐数


时间轴

时间轴

2025-11-13

init

哈希表

题目:

循环类似 for 循环,就写成 for 循环的形式了。

123456789101112131415161718192021222324252627282930313233
#include <unordered_set>using std::unordered_set;class Solution {    public:	int ops(int n)	{		int res = 0;		int num;		while (n) {			num = n % 10;			res += num * num;			n /= 10;		}		return res;	}	bool isHappy(int n)	{		unordered_set<int> numbers;		int i;				for (i = n; numbers.count(i) == 0; i = ops(i)) {			if (i == 1) {				return true;			}			numbers.insert(i);		}		return false;	}};
评论加载中…