TARGET DECK: Leetcode FILE TAGS: Easy


Complexity

Runtime

Space

Code

C++

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> res(n);
        for(int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                res[i - 1] = "FizzBuzz"; 
            } else if (i % 3 == 0) {
                res[i - 1] = "Fizz";
            } else if (i % 5 == 0) {
                res[i - 1] = "Buzz";
            } else {
                res[i - 1] = std::to_string(i);
            }
        } // end for
 
        return res;
    } // end fizzBuzz
};

C

 
 
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** fizzBuzz(int n, int* returnSize) {
    // Hold the size of the string pointer, which is 4 bytes.
        // i.e. an address in memory takes up 4 bytes, so you store that address in memory
    char **answer = malloc((n + 1) * sizeof(char *));
    for (int i = 1; i <= n; i++) {
        if (i % 3 == 0 && i % 5 == 0) {
            answer[i - 1] = "FizzBuzz";
        } else if (i % 3 == 0) {
            answer[i - 1] = "Fizz";
        } else if (i % 5 == 0) {
            answer[i - 1] = "Buzz";
        } else {
            // n is at most 10^4, which is 10,000 i.e. 5 bytes
            answer[i - 1] = malloc((5 + 1) * sizeof(char));
            sprintf(answer[i - 1], "%d", i);
        }
    } // end for
 
    *returnSize = n;
    return answer;
} // end fizzBuzz

Cards

START Basic Front: Fizz Buzz Back: Make sure you are 1-indexed

END


References