
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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5char** fizzBuzz(int n, int* returnSize) {
6 char** result = (char**)malloc(n * sizeof(char*));
7 *returnSize = n;
8 for (int i = 1; i <= n; i++) {
9 if (i % 3 == 0 && i % 5 == 0) {
10 result[i - 1] = strdup("FizzBuzz");
11 } else if (i % 3 == 0) {
12 result[i - 1] = strdup("Fizz");
13 } else if (i % 5 == 0) {
14 result[i - 1] = strdup("Buzz");
15 } else {
16 result[i - 1] = (char*)malloc(12 * sizeof(char));
17 sprintf(result[i - 1], "%d", i);
18 }
19 }
20 return result;
21}
22The function fizzBuzz takes an integer n and generates an array of strings. It checks each number from 1 to n for divisibility by 3 and 5. The use of strdup efficiently allocates memory for the strings returned.
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#
This C solution defines a constant array storing potential word outputs for Fizz, Buzz, and FizzBuzz. Indexes based on divisibility determine which string to select, reducing the number of branch conditions.