FizzBuzz

Easy

Write a program that outputs the string representation of numbers from 1 to n. For multiples of 3 output 'Fizz', for multiples of 5 output 'Buzz', and for multiples of both 3 and 5 output 'FizzBuzz'.

Examples

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

Python Solution

def fizzbuzz(n: int) -> list[str]:
    result = []
    for i in range(1, n + 1):
        if i % 15 == 0:
            result.append("FizzBuzz")
        elif i % 3 == 0:
            result.append("Fizz")
        elif i % 5 == 0:
            result.append("Buzz")
        else:
            result.append(str(i))
    return result

JavaScript Solution

function fizzBuzz(n) {
  const result = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) result.push("FizzBuzz");
    else if (i % 3 === 0) result.push("Fizz");
    else if (i % 5 === 0) result.push("Buzz");
    else result.push(String(i));
  }
  return result;
}

Step-by-Step Explanation

  1. Iterate from 1 to n.
  2. Check divisibility by 15 first (both 3 and 5).
  3. Then check 3 (Fizz) and 5 (Buzz) separately.
  4. Otherwise append the number as a string.

Complexity Analysis

TimeO(n)
SpaceO(1) excluding output

Tags

MathString

Related Problems

All Problems