-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHappyNumber.java
41 lines (31 loc) · 1.05 KB
/
HappyNumber.java
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
public class HappyNumber {
// ************* LEETCODE PROBLEM 202 *******************
// This solution uses Floyd Cycle detection algorithm and modulus to get individual digits of numbers
class Solution {
public boolean isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = sumOfDigits(slow);
fast = sumOfDigits(sumOfDigits(fast));
if(slow == 1) {return true;}
}
while(slow != fast);
return false;
}
public int sumOfDigits(int n) {
int sum = 0;
// get sum of digits of current pass
while (n > 0) {
// Get one's place digit seperately
int remainder = n % 10;
int squareDigit = remainder * remainder;
// move the number down one tenths place
n = n / 10;
// add squared digit to sum
sum += squareDigit;
}
return sum;
}
}
}