Fizz Buzz
Fizz Buzz
MathString
Problem Statement
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
ifi
is divisible by 3 and 5.answer[i] == "Fizz"
ifi
is divisible by 3.answer[i] == "Buzz"
ifi
is divisible by 5.answer[i] == i
(as a string) if none of the above conditions are true.
Example
Example 1:
Input: n = 15
For n = 15:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Solution (Simple Iteration)
The FizzBuzz problem is a classic programming task that tests basic loop and conditional logic. The approach is to iterate from 1 to n and apply a set of rules.
Algorithm Steps
- Initialize an empty list or array to store the results.
- Loop from 1 to
n
. - For each number, first check if it's divisible by both 3 and 5. If so, add "FizzBuzz" to your list.
- If not, check if it's divisible by 3. If so, add "Fizz".
- If not, check if it's divisible by 5. If so, add "Buzz".
- If none of the above are true, add the number itself (as a string) to the list.
- After the loop finishes, return the list of results.
Current Number (i)
-
Result Array
[]
Start with n = 15.
Fizz Buzz Solution