leetcode412题解

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刷题题解,当做记录,也是激励吧~
日积跬步,终至千里。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值