Skip to content

Commit d9a14aa

Browse files
author
ChienkuChen
committed
Add 202
1 parent c4ddd27 commit d9a14aa

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/_202/202.happy-number.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package _202;
2+
3+
class Solution {
4+
public boolean isHappy(int n) {
5+
// because if it isn't a happy number, it loops endlessly in a cycle which does not include 1.
6+
// I remind the algorithm of detecting a cycle
7+
8+
int slow = n;
9+
int fast = n;
10+
11+
do {
12+
slow = sum(slow);
13+
fast = sum(sum(fast));
14+
} while (slow != fast && slow != 1);
15+
16+
return slow == 1;
17+
}
18+
19+
private int sum(int n) {
20+
int sum = 0;
21+
while (n > 0) {
22+
sum += Math.pow(n % 10, 2);
23+
n /= 10;
24+
}
25+
26+
return sum;
27+
}
28+
29+
public static void main(String[] args) {
30+
System.out.println(new Solution().isHappy(19));
31+
System.out.println(new Solution().isHappy(14));
32+
}
33+
}

0 commit comments

Comments
 (0)