Skip to content

Commit c677a7e

Browse files
authored
Update Happy Number.java
1 parent 81e6e85 commit c677a7e

File tree

1 file changed

+11
-17
lines changed

1 file changed

+11
-17
lines changed

Easy/Happy Number.java

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,21 @@
11
class Solution {
22
public boolean isHappy(int n) {
3-
Set<Integer> set = new HashSet<>();
4-
set.add(n);
5-
while (true) {
6-
int sumOfDigitSquare = getSumOfDigitSquare(n);
7-
if (sumOfDigitSquare == 1) {
8-
return true;
9-
}
10-
if (set.contains(sumOfDigitSquare)) {
11-
break;
12-
}
13-
set.add(sumOfDigitSquare);
14-
n = sumOfDigitSquare;
3+
int slow = n;
4+
int fast = getSquareDigitSum(n);
5+
while (fast != 1 && slow != fast) {
6+
slow = getSquareDigitSum(slow);
7+
fast = getSquareDigitSum(getSquareDigitSum(fast));
158
}
16-
return false;
9+
return fast == 1;
1710
}
1811

19-
private int getSumOfDigitSquare(int n) {
20-
int sum = 0;
12+
private int getSquareDigitSum(int n) {
13+
int squareDigitSum = 0;
2114
while (n > 0) {
22-
sum += (int) Math.pow(n % 10, 2);
15+
int digit = n % 10;
16+
squareDigitSum += digit * digit;
2317
n /= 10;
2418
}
25-
return sum;
19+
return squareDigitSum;
2620
}
2721
}

0 commit comments

Comments
 (0)