您的位置:首页 > 其它

LeetCode 412. Fizz Buzz

2017-07-14 10:40 302 查看

412. Fizz Buzz

Description

Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example :

n = 15,

Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]


Solution

//题目的意思就是将1-n 这些数按照一定规则转换成字符串
//规则就是3的倍数转换成Fizz,5的倍数转换成Buzz,3、5的公倍数转换成FizzBuzz,其余的数字转换成对应字符串即可
//将数字转换成字符串有多种方法,比如itoa(),这里用的是sprintf,代码如下

char** fizzBuzz(int n, int* returnSize) {
char **rnt = (char **)malloc(sizeof(char *) * (n + 1));
for (int i = 0;i <= n;i++) {
rnt[i] = (char *)malloc(sizeof(char) * 5);
}
for (int i = 1;i <= n;i++) {
if (i % 3 == 0 && i % 5 == 0) {
strcpy(rnt[i - 1],"FizzBuzz");
}
else if (i % 3 == 0) {
strcpy(rnt[i - 1],"Fizz");
}
else if (i % 5 == 0) {
strcpy(rnt[i - 1],"Buzz");
}
else {
sprintf(rnt[i - 1],"%d",i);
}
}
*returnSize = n;
return rnt;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c