-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHappyNumber.cpp
49 lines (44 loc) · 977 Bytes
/
HappyNumber.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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/*
bool isHappy(int n) {
while (1) {
int nn = 0;
if (n < 10) break;
while (n) {
nn += (n%10) * (n%10);
n /= 10;
}
n = nn;
}
if (n == 1 || n == 7) return true;
return false;
}
*/
int next(int n) {
int nn = 0;
while (n) {
nn += (n%10) * (n%10);
n /= 10;
}
return nn;
}
bool isHappy(int n) {
int slow = next(n);
int fast = next(next(n));
while(slow != fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast == 1;
}
};
int main() {
Solution obj;
int n = 7;
bool ans = obj.isHappy(n);
cout << "n:: " << ans << endl;
return 0;
}