Sponsored
Sponsored
This approach iterates through numbers from 1 to n and applies conditional logic using modulus operations to determine if a number should be represented as "Fizz", "Buzz", or "FizzBuzz". If none of these conditions are met, the number itself is returned as a string.
Time Complexity: O(n)
as we iterate through each number from 1 to n
once.
Space Complexity: O(n)
for the output array.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<string> FizzBuzz(int n) {
6 IList<string> result = new List<string>();
7 for (int i = 1; i <= n; i++) {
8 if (i % 3 == 0 && i % 5 == 0) {
9 result.Add("FizzBuzz");
10 } else if (i % 3 == 0) {
11 result.Add("Fizz");
12 } else if (i % 5 == 0) {
13 result.Add("Buzz");
14 } else {
15 result.Add(i.ToString());
16 }
17 }
18 return result;
19 }
20}
21
In this C# variant, the solution leverages a List
to store results. Conditional statements check each number for divisibility to decide what string should be appended.
This approach uses a hash map to store possible outputs, simplifying conditional checks. By mapping integers to their respective Fizz
or Buzz
values, we consolidate decision logic, reducing redundancy in the code.
Time Complexity: O(n)
, since each element is evaluated once.
Space Complexity: O(n)
due to storage for result strings.
1import
This Java implementation uses an array for the standard outputs. It calculates which output to use by computing an index, simplifying the branch logic typically involved in such solutions.