Happy Number LeetCode solution in Java

1
class Solution {
2
public boolean isHappy(int n) {
3
// Create a hash set...
4
Set<Integer> hset = new HashSet<Integer>();
5
// If the number is not in the HashSet, we should add it...
6
while (hset.add(n)) {
7
// Initialize the total...
8
int total = 0;
9
// Create a while loop...
10
while (n > 0) {
11
// Process to get happy number...
12
// We use division and modulus operators to repeatedly take digits off the number until none
13
// remain...
14
// Then squaring each removed digit and adding them together...
15
total += (n % 10) * (n % 10);
16
n /= 10;
17
// Each new converted number must not had occurred before...
18
}
19
// If total is equal to 1 return true.
20
if (total == 1) return true;
21
// Insert the current number into the set s...
22
// Replace the current number with total of the square of its digits.
23
else n = total;
24
}
25
// If current number is already in the HashSet, that means we're in a cycle and we should return
26
// false..
27
return false;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0