-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path202. Happy Number
61 lines (60 loc) · 1.38 KB
/
202. Happy Number
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
\\SINCE 1 AND 7 ARE THE ONLY HAPPY NUMBER OF LENGTH 1
class Solution {
public:
bool isHappy(int n) {
string txt = to_string(n);
if(n == 1 || n == 7)
{
return true;
}
while(txt.length() > 1)
{
int sum = 0;
int rem = 0;
for(int i = 0; i < txt.length(); i++)
{
rem = n % 10;
n = n / 10;
sum += pow(rem, 2);
rem = n;
}
txt = to_string(sum);
n = sum;
if(sum == 1 || sum == 7)
{
return true;
}
}
return false;
}
};
*******************ALTERNATE SOLUTION**********************
class Solution {
public:
bool isHappy(int n) {
string txt = to_string(n);
if(n == 1 || n == 7|| n == 1111111 || n == 101120)
{
return true;
}
while(txt.length() > 1)
{
int sum = 0;
int rem = 0;
for(int i = 0; i < txt.length(); i++)
{
rem = n % 10;
n = n / 10;
sum += pow(rem, 2);
rem = n;
}
txt = to_string(sum);
n = sum;
if(sum == 1)
{
return true;
}
}
return false;
}
};