FizzBuzz
FizzBuzz is a counting game. Players count up from 1, but some numbers are replaced by words: a number divisible by 3 is said as Fizz, a number divisible by 5 as Buzz, and a number divisible by both 3 and 5 as FizzBuzz. Every other number is said as it is. The first fifteen turns go 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz.
The order of the checks is the whole trick. 15 is divisible by 3, so if you test for 3 first and return "Fizz" right away, you never reach the case for both. Check the combined rule first: a number divisible by both 3 and 5 is exactly a number divisible by 15. Then check 3, then 5, and only then fall back to the number itself.
The classic version prints the whole sequence. Here you answer for one number at a time: given n, return what a player says on turn n. For example, turn 9 is "Fizz", turn 10 is "Buzz" and turn 11 is "11".
Write a function named fizzBuzz that gets a positive integer n and returns a string: "FizzBuzz" if n is divisible by both 3 and 5, "Fizz" if it is divisible by 3 only, "Buzz" if it is divisible by 5 only, and otherwise n written as a decimal string (for example "7").
Constraints: 1 <= n <= 10^9.
Function
- arg1integer
- Returnsstring
Examples
- Input
- arg1 = 15
- Output
- "FizzBuzz"
- Input
- arg1 = 7
- Output
- "7"
+11 hidden tests on Submit
Hints
Open them one at a time. Each one gives away a little more.
The remainder operator tells you whether one number divides another:
nis divisible by 3 exactly when the remainder ofndivided by 3 is 0.Think about 15. It is divisible by 3 and by 5. Which of your checks should run first so that 15 gets
"FizzBuzz"and not"Fizz"?Test divisibility by 15 first, then by 3, then by 5. If none match, convert the number to a string. Make sure the conversion writes every digit, so 10^9 comes out as
"1000000000"and not in scientific notation.
A full walkthrough of this problem is on its way.
Similar problems
Problems that use the same ideas. Solving two or three of them is what makes a pattern stick.
Python
def fizzBuzz(n):
# Write code hereCase 1
Case 2
Input
arg1 = 15
Expected
"FizzBuzz"