- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHappyNumber.java
More file actions
Latest commit
41 lines (31 loc) · 1.05 KB
/
Copy pathHappyNumber.java
File metadata and controls
41 lines (31 loc) · 1.05 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
publicclassHappyNumber {
// ************* LEETCODE PROBLEM 202 *******************
// This solution uses Floyd Cycle detection algorithm and modulus to get individual digits of numbers
classSolution {
publicbooleanisHappy(intn) {
intslow = n;
intfast = n;
do {
slow = sumOfDigits(slow);
fast = sumOfDigits(sumOfDigits(fast));
if(slow == 1) {returntrue;}
}
while(slow != fast);
returnfalse;
}
publicintsumOfDigits(intn) {
intsum = 0;
// get sum of digits of current pass
while (n > 0) {
// Get one's place digit seperately
intremainder = n % 10;
intsquareDigit = remainder * remainder;
// move the number down one tenths place
n = n / 10;
// add squared digit to sum
sum += squareDigit;
}
returnsum;
}
}
}