LeetCode 412 FizzBuzz
https://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”.
写一个程序,输出从1到n全部数字的字符串形式。但是,如果这个数字是3的倍数,则输出“Fizz”,而不要输出数字本身;同理,如果这个数字是5的倍数,则要输出“Buzz”;如果这个数字既是3的倍数也是5的倍数,则输出“FizzBuzz”。
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”.
写一个程序,输出从1到n全部数字的字符串形式。但是,如果这个数字是3的倍数,则输出“Fizz”,而不要输出数字本身;同理,如果这个数字是5的倍数,则要输出“Buzz”;如果这个数字既是3的倍数也是5的倍数,则输出“FizzBuzz”。
I write code in C to slove this problem, but I get two troubles about this question.
1)I can not convert an integer into a string when the integer is greater than 9, for example, I know that char '9' can be print as 9+'0', which is its char expression of char '9', but I do not know how to express '15' in char/string.
2)Even the output is in integer, my code is shown to be output nothing after I submit my code to leetcode, while my code has the correct result in my own PC. I use DEV-C++(version 5.11)
我用C语言写的这个程序,但是遇到2个问题。
1)不知道咋把整数转换成字符串形式,尤其是当数字是两位数以上的时候。例如我知道整数9可以用9+'0'的形式输出,就是输出char类型的9,但是如果是数字15,我就不知道怎么转换成string形式了。
2)即便是输出整数形式,我的代码似乎也是不成功的,例如,对于输入n = 1, 我自己的电脑上显示成功输出了"1",但是把代码提交到Leetcode上去,就显示输出为空。我用Dec-C++写的代码,版本是5.11。
My code in C is shown below:
程序代码:
#include <stdio.h> #include <stdlib.h> int main (int argc, char* argv[]) { int num, i; scanf("%d", &num); for (i = 1; i <= num; i++) { if (i%3 == 0 && i%5 == 0){ //if num is the multiples of 3 and also the multiples of 5, print "FizzBuzz" printf("\"FizzBuzz\",\n"); } else if (i%3 == 0) { printf("\"Fizz\",\n"); //if num is the multiples of 3, print "Fizz" } else if (i%5 == 0){ printf("\"Buzz\",\n"); //if num is the multiples of 5, print "Buzz" } else { printf("\"%d\",\n", i); //if nothing happens above, just print the integer itself out } } return 0; }
Thank you so much for pointing out my mistakes and thank you so so much for correcting them !!!!!
[此贴子已经被作者于2016-12-9 05:27编辑过]