-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhappy-number.cpp
60 lines (55 loc) · 1.2 KB
/
happy-number.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
instead calculcating the same numbers over and over again pre-calculated map is used.
but since hash function in the hashmap also does some calculcation and uses cpu cycle,
the runtime does not differ.
*/
class Solution {
public:
unordered_set<int> seen_before;
map<int, int> m = {
{0, 0},
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
};
bool isHappy(int n) {
int total = 0;
while(n > 0){
total += m[n % 10];
n /= 10;
}
if(total == 1){
return true;
}
if(seen_before.find(total) != seen_before.end()){
return false;
}
seen_before.insert(total);
return isHappy(total);
}
};
class Solution {
public:
unordered_set<int> seen_before;
bool isHappy(int n) {
int total = 0;
while(n > 0){
total += pow((n % 10), 2);
n /= 10;
}
if(total == 1){
return true;
}
if(seen_before.find(total) != seen_before.end()){
return false;
}
seen_before.insert(total);
return isHappy(total);
}
};