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.Collections.Generic;
public class Solution {
public IList<string> FizzBuzz(int n) {
IList<string> result = new List<string>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
result.Add("FizzBuzz");
} else if (i % 3 == 0) {
result.Add("Fizz");
} else if (i % 5 == 0) {
result.Add("Buzz");
} else {
result.Add(i.ToString());
}
}
return result;
}
}
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.
1#include <vector>
2#include <string>
3
4std::vector<std::string> fizzBuzz(int n) {
5 const std::string values[4] = { "", "Fizz", "Buzz", "FizzBuzz" };
6 std::vector<std::string> result(n);
7 for (int i = 1; i <= n; ++i) {
8 int index = (i % 15 == 0) ? 3 : (i % 3 == 0) ? 1 : (i % 5 == 0) ? 2 : 0;
9 result[i - 1] = (index == 0) ? std::to_string(i) : values[index];
10 }
11 return result;
12}
13
The C++ version employs an array of strings and refers to it directly. By determining the index based on divisibility checks, the correct string is selected with minimal conditional checks.