Read the question, write Java on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Collatz steps from n to 1.
Examples
Input
6
Output
8
Input
1
Output
0
Hint
- even: n/=2; odd: n=3*n+1
Show correct code
Peek only after you have tried. You can still Check your own version.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int steps = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
System.out.println(steps);
}
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.