-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHappyNumber.java
More file actions
56 lines (45 loc) · 1.13 KB
/
HappyNumber.java
File metadata and controls
56 lines (45 loc) · 1.13 KB
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
package math;
import java.util.HashSet;
import java.util.Set;
/**
* Description: https://leetcode.com/problems/happy-number
* Difficulty: Easy
*/
public class HappyNumber {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public boolean isHappyViaSet(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1) {
if (!seen.add(n)) return false;
n = sumOfSquares(n);
}
return true;
}
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public boolean isHappyViaLinkedListCycleDetection(int n) {
int slow = n;
int fast = n;
do {
slow = sumOfSquares(slow);
fast = sumOfSquares(sumOfSquares(fast));
if (fast == 1) return true;
} while (slow != fast);
// [17] -> 50 -> 25 -> 29 -> 85 -> 89 -> 145 -> 41 -> [17]
return false;
}
private int sumOfSquares(int n) {
int sum = 0;
while (n != 0) {
int digit = n % 10;
sum += digit * digit;
n = n / 10;
}
return sum;
}
}