File tree Expand file tree Collapse file tree 1 file changed +11
-17
lines changed Expand file tree Collapse file tree 1 file changed +11
-17
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
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 ));
15
8
}
16
- return false ;
9
+ return fast == 1 ;
17
10
}
18
11
19
- private int getSumOfDigitSquare (int n ) {
20
- int sum = 0 ;
12
+ private int getSquareDigitSum (int n ) {
13
+ int squareDigitSum = 0 ;
21
14
while (n > 0 ) {
22
- sum += (int ) Math .pow (n % 10 , 2 );
15
+ int digit = n % 10 ;
16
+ squareDigitSum += digit * digit ;
23
17
n /= 10 ;
24
18
}
25
- return sum ;
19
+ return squareDigitSum ;
26
20
}
27
21
}
You can’t perform that action at this time.
0 commit comments