--- title: 'LeetCode 412. Fizz Buzz' disqus: hackmd --- # LeetCode 412. Fizz Buzz ## Description Given an integer n, return a string array answer (1-indexed) where: * answer[i] == "FizzBuzz" if i is divisible by 3 and 5. * answer[i] == "Fizz" if i is divisible by 3. * answer[i] == "Buzz" if i is divisible by 5. * answer[i] == i (as a string) if none of the above conditions are true. ## Example Input: n = 3 Output: ["1","2","Fizz"] Input: n = 5 Output: ["1","2","Fizz","4","Buzz"] ## Constraints 1 <= n <= 10^4^ ## Answer 此題主要是考雙重指標,取餘數為0給定不同字串。在數字時注意使用 "snprintf" function可以將數字化成字串。 ```Cin= //2022_03_13 void mystrcpy(char *s, char *t); char ** fizzBuzz(int n, int* returnSize){ char **ans = (char**)malloc(sizeof(char*)*n); *returnSize = 0; char *FB = "FizzBuzz", *F = "Fizz", *B = "Buzz"; for(int i = 1; i <= n; i++){ if(i%3==0 && i%5==0){ ans[*returnSize] = (char*)malloc(sizeof(char)*9); mystrcpy(ans[*returnSize],FB); } else if(i%3==0){ ans[*returnSize] = (char*)malloc(sizeof(char)*5); mystrcpy(ans[*returnSize],F); } else if(i%5==0){ ans[*returnSize] = (char*)malloc(sizeof(char)*5); mystrcpy(ans[*returnSize],B); } else{ ans[*returnSize] = (char*)malloc(sizeof(char)*5); snprintf(ans[*returnSize],10,"%d",i); } (*returnSize)++; } return ans; } void mystrcpy(char *s, char *t){ while(*t != '\0'){ *s++ = *t++; } *s = '\0'; } ``` ## Link https://leetcode.com/problems/fizz-buzz/ ###### tags: `Leetcode`