Skip to content

Commit c273465

Browse files
committed
Solution without HashSet
1 parent e0ca375 commit c273465

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed

Java/Happy-Number.java

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,31 @@
1-
class Solution {
1+
class HappyNumber {
22
public boolean isHappy(int n) {
3-
4-
Set<Integer> unique = new HashSet<Integer>();
3+
int num1, num2;
4+
5+
num1 = num2 = n;
6+
do
7+
{
8+
num1 = SquareSum(num1);
9+
10+
11+
num2 = SquareSum(SquareSum(num2));
12+
13+
}
14+
while (num1 != num2);
15+
16+
return (num1 == 1);
17+
}
518

6-
while (unique.add(n))
7-
{
8-
int value = 0;
9-
while (n > 0)
10-
{
11-
value += Math.pow(n % 10, 2);
12-
n = n/10;
13-
}
14-
n = value;
15-
}
1619

17-
18-
if(n == 1)
19-
return true;
20-
else
21-
return false;
22-
23-
}
20+
static int SquareSum(int n)
21+
{
22+
int square = 0;
23+
while (n!= 0)
24+
{
25+
square += (n % 10) * (n % 10);
26+
n /= 10;
27+
}
28+
return square;
29+
}
30+
2431
}

0 commit comments

Comments
 (0)