[GO] [Java] Try to solve the Fizz Buzz problem using recursive processing
Introduction
- After posting "[Java] Try to solve the Fizz Buzz problem" before, I was wondering if I could write it in a different way.
- Focusing on the point that "the number of judgments increases by 1," I thought that recursive processing could be used, so I tried it.
Code created
- The first conditional branch, ʻif (end> 1) {...}
, prevents further recursive processing when ʻend == 1
.
- It meets FizzBuzz's rule that "the first player reads out the number" 1 "".
FizzBuzz2.java
/**
*A method that utilizes recursive processing.
* @param end The number to end FizzBuzz.
*/
public static void useRecursion(int end) {
if (end > 1) {
useRecursion(end - 1);
}
if (end%3==0 && end%5==0) {
System.out.println("Fizz Buzz");
} else if (end%3==0) {
System.out.println("Fizz");
} else if (end%5==0) {
System.out.println("Buzz");
} else {
System.out.println(end);
}
}
Execution result (* When 20 is specified for the argument end)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
16
17
Fizz
19
Buzz
Summary
- I was able to solve the FizzBuzz problem using recursive processing.
- However, if the argument ʻend` becomes large, the number of recursive processing (recursive function) calls also increases, so there is a risk of stack overflow.