Cover image for Classic Interview 150 Questions P202 Happy Number

Classic Interview 150 Questions P202 Happy Number


Timeline

Timeline

2025-11-13

init

Hash table

Problem:

The loop is similar to a for loop, so I wrote it in the form of a for loop.

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;	}};
Loading comments…