leetcode412题解

来源:互联网 发布:pro tools 12.8.2 mac 编辑:程序博客网 时间:2024/05/16 06:02

leetcode 412.Fizz Buzz

题目

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”.

翻译成中文就是,遇到3的倍数输出“Fizz”,遇到5的倍数输出“Buzz”,同时为3和5的倍数输出“FizzBuzz”,其余数字则直接输出。

解题思路

判断是否为k的倍数,只需要判断 i%k==0 即可,本题难点在于如何把只需输出自身数字的整型变量转换为字符串变量。

在C++中转换int型为string的方法有两种:

http://blog.csdn.net/chavo0/article/details/51038397

第一种是to_string函数,这是C++11新增的。直接调用该函数就可以。
第二种是借助字符串流

ostringstream stream;stream<<n;  //n为int类型return stream.str();

AC代码如下

class Solution {public:vector<string> fizzBuzz(int n) { int i; vector<string> ans(n); string str1="Fizz"; string str2="Buzz"; for(int i=1;i<=n;i++){    if(i%3==0)        ans[i-1]+=str1;    if(i%5==0)        ans[i-1]+=str2;    if(i%3!=0&&i%5!=0)  //此处判断条件也可替换为 ans[i-1]==""        ans[i-1]+=to_string(i); } return ans;}};

AC时间为3ms,判断条件替换后时间未变。另外leetcode讨论区中还有几种方法,如不用%运算符,而用mul3、mul5两个变量来标识3或5的倍数,AC时间无明显提高。

总结

本题是leetcode Top Interview Questions 中第一题,难度为easy。
题目自身难度很小,主要是知道了C++中转换int为string的方法即可。


目前计划为在CSDN和GitHub同步更新leetcode刷题题解,当做记录,也是激励吧~
日积跬步,终至千里。