-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path202. Happy Number
64 lines (59 loc) · 1.66 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
62
63
64
/* I use square_digit to get the sume of the square of the digits,
then in the isHappy we build a set, every time the sum obtained by square_digit, we will check if it is in the hashset until the number
becomes 1. If the number successfully becomes 1, it is a happy number. Otherwise, it shows in the hashset, it will be not a happy number
hashset.add() returns a boolean value, if the item successfully adds in the set, it will return true, otherwise it will return false.
*/
public class Solution {
public int square_digit(int n)
{
int sum=0;
int i=0;
for(i=0;i<32;i++)
{ int residual=n%10;
if(n==0)
break;
sum+=residual*residual;
n=n/10;
}
return sum;
}
public boolean isHappy(int n) {
HashSet<Integer> res = new HashSet<Integer>();
if(n<=0)
return false;
while(n!=1)
{
if(res.add(n))
n=square_digit(n);
else
return false;
}
return true;
}
}
//第二次做的
public class Solution {
public boolean isHappy(int n) {
if(n<=0)
return false;
Set<Integer> reserve= new HashSet<Integer>();
while(sqOfDigits(n)!=1)
{if(!reserve.add(sqOfDigits(n)))
break;
n=sqOfDigits(n);
}
return sqOfDigits(n)==1;
}
public int sqOfDigits(int n)
{ ArrayList<Integer> sq =new ArrayList<Integer>();
while(n/10!=0)
{sq.add(n%10);
n=n/10;
}
sq.add(n%10);
int sum=0;
for (int i=0; i<sq.size();i++)
sum+=sq.get(i)*sq.get(i);
return sum;
}
}