Finish challenge Happy Number
This commit is contained in:
parent
12a2456b59
commit
2e26a9d667
3 changed files with 46 additions and 0 deletions
11
cediackermann/challenges/happyNumber/BUILD
Normal file
11
cediackermann/challenges/happyNumber/BUILD
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
load("@rules_java//java:defs.bzl", "java_binary")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
java_binary(
|
||||
name = "happyNumber",
|
||||
main_class = "cediackermann.challenges.happyNumber.Main",
|
||||
srcs = glob(["*.java"]),
|
||||
deps = [
|
||||
],
|
||||
)
|
||||
8
cediackermann/challenges/happyNumber/Main.java
Normal file
8
cediackermann/challenges/happyNumber/Main.java
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
package cediackermann.challenges.happyNumber;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Solution sol = new Solution();
|
||||
System.out.println(sol.isHappy(2));
|
||||
}
|
||||
}
|
||||
27
cediackermann/challenges/happyNumber/Solution.java
Normal file
27
cediackermann/challenges/happyNumber/Solution.java
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
package cediackermann.challenges.happyNumber;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Solution {
|
||||
public boolean isHappy(int n) {
|
||||
Set<Integer> seen = new HashSet<>();
|
||||
|
||||
while (n != 1 && !seen.contains(n)) {
|
||||
seen.add(n);
|
||||
n = getNextGen(n);
|
||||
}
|
||||
|
||||
return n == 1;
|
||||
}
|
||||
|
||||
private int getNextGen(int n) {
|
||||
int nextGen = 0;
|
||||
while (n > 0) {
|
||||
int digit = n % 10;
|
||||
nextGen += digit * digit;
|
||||
n /= 10;
|
||||
}
|
||||
return nextGen;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue