-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0202_Happy-Number.cpp
More file actions
49 lines (48 loc) · 1.13 KB
/
0202_Happy-Number.cpp
File metadata and controls
49 lines (48 loc) · 1.13 KB
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
// brute force method
class Solution {
public:
long long int result(long long int n) {
long long int ans = 0;
while (n) {
ans += (n % 10) * (n % 10);
n /= 10;
}
return ans;
}
bool isHappy(int n) {
unordered_map<int, bool> record;
long long int tmp;
while (true) {
tmp = result(n);
if (record.count(tmp))
return false;
else
record.emplace(tmp, true);
n = tmp;
if (n == 1)
return true;
}
return false;
}
};
// since we want to know whether it has cycle or not.
// We can use slow and fast pointer!
class Solution {
public:
long long int result(long long int n) {
long long int ans = 0;
while (n) {
ans += (n % 10) * (n % 10);
n /= 10;
}
return ans;
}
bool isHappy(int n) {
long long int slow = n, fast = n;
do {
slow = result(slow);
fast = result(result(fast));
} while (slow != fast);
return slow == 1;
}
};