Algorithm Puzzles: Happy Number

Algorithm Puzzles everyday every week sometimes: Happy Number

Puzzle

Puzzle from leetcode:

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
bool isHappy(int n) {
std::unordered_set<int> occurredSet;
occurredSet.insert(n);
int sum = 0;
while(n > 0) {
int digit = n % 10;
sum += (digit * digit);
n /= 10;
if (n == 0) {
if (sum == 1) {
return true;
}
if (occurredSet.count(sum) > 0) {
return false;
}
occurredSet.insert(sum);
n = sum;
sum = 0;
}
}

return false;
}
};

T.C.: O(N)
S.C.: O(N)