-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhappy.cpp
More file actions
70 lines (61 loc) · 1.34 KB
/
happy.cpp
File metadata and controls
70 lines (61 loc) · 1.34 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
using namespace std;
class Solution {
public:
/*int getNext(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int seen[1000]; // Array to store seen numbers
int index = 0;
while (n != 1) {
for (int i = 0; i < index; i++) {
if (seen[i] == n) return false; // Cycle detected
}
seen[index++] = n;
n = getNext(n);
}
return true;
}*/
/* bool isHappy(int n) {
int slow = n, fast = getNext(n);
while (fast != 1 && slow != fast) {
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast == 1;
}*/
int getnext(int n){
int d,sum=0;
while(n>0){
d=n%10;
n=n/10;
sum+=d*d;
}
return sum;
}
bool isHappy(int n){
int slow=n,fast=getnext(n);
while (fast != 1 && slow!=fast){
slow=getnext(slow);
fast=getnext(getnext(fast));
}
return fast==1;
}
};
int main() {
int n;
cin >> n;
Solution obj;
if (obj.isHappy(n))
cout << "True\n";
else
cout << "False\n";
return 0;
}