Fizz and buzz
Count up, and say a word instead of the number when a rule fits. About 12 minutes.
No label this time
From here on, the steps don't tell you which idea to use. A problem arrives with no label, and you decide which tools to reach for. Before you start, ask: what am I repeating, what choices do I make each time, and what do I build up?
A small hint for this one. Some numbers fit more than one rule, such as 15, which is a multiple of 3 and of 5. When one number fits two rules, the order you ask the questions in decides the answer.
- i
- 1
- word
- 1
1 is not a multiple of 3 or 5, so the word is the number itself, as text.
Why should the question for numbers that are multiples of both 3 and 5 come first?
- AOtherwise 15 would match the Fizz question first, and the answer would be wrong
- BIt makes the code run faster
- CThe order doesn't matter
Show the answer
Otherwise 15 would match the Fizz question first, and the answer would be wrong. The first true question wins. 15 is a multiple of 3, so it would stop at Fizz and never reach the both-rule.
Fizz buzz
Return a list with one text for each number from 1 to n. If the number is a multiple of both 3 and 5, the text is "FizzBuzz". If it is a multiple of 3 only, the text is "Fizz". If it is a multiple of 5 only, the text is "Buzz". Otherwise the text is the number itself, written as text.
n = 5 → ["1", "2", "Fizz", "4", "Buzz"]
0 ≤ n ≤ 1,000