We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c4ddd27 commit d9a14aaCopy full SHA for d9a14aa
src/_202/202.happy-number.java
@@ -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