Happy Number LeetCode solution in C++

1
class Solution {
2
public:
3
bool isHappy(int n) {
4
// Create a set...
5
set<int> hset;
6
while (hset.count(n) == 0) {
7
// If total is equal to 1 return true.
8
if (n == 1) return true;
9
// Insert the current number in hset...
10
hset.insert(n);
11
// Initialize the total...
12
int total = 0;
13
// Create a while loop...
14
while (n) {
15
// Process to get happy number...
16
// We use division and modulus operators to repeatedly take digits off
17
// the number until none remain... Then squaring each removed digit and
18
// adding them together.
19
total += (n % 10) * (n % 10);
20
n /= 10;
21
// Each new converted number must not had occurred before...
22
}
23
// Insert the current number into the set s...
24
// Replace the current number with total of the square of its digits.
25
n = total;
26
}
27
// If current number is already in the HashSet, that means we're in a cycle
28
// and we should return false..
29
return false;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0