Leetcode Algorithm

412. Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

Logic:

  1. Create an empty list as “ans”
  2. Loop from 1 to n, and check each values in the loop. Check them with 15 firstly, and then 5, and then 3. Use modulus to check each values
  3. Notice that the output list is a list of strings. So, we have to convert the values in the step 2 to strings, before appending them in a list.

Solution:

class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for x in range(1, n+1):
n = str(x) # convert int to string
if x % 15 == 0: # multiplier of 15
n = "FizzBuzz"
elif x % 5 == 0:
n = "Buzz"
elif x % 3 == 0:
n = "Fizz"
ans.append(n)
return ans

Link

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store