LeetCode

1.题目大意

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

给定一个数n,要求写出代表1到n的字符串,其中能被3整除的输出 “Fizz”,能被5整除的输出 “Buzz”,同时被3和5整除的输出 “FizzBuzz”。

2.思路

思路非常简单。是个人应该都能做出来。但有几点可以学习一下,一个是C++中vector的应用(可以参考这篇文章),另一个是C++中int转string的方法。

下面是int转string的几种思路:

(1)利用stringstream:

使用stringstream的时候要注意加#include"sstream"。比如说我要把int类型的23转为string类型,那么我可以这样实现:

    int a=23;
    stringstream ss;
    ss<<a;
    string s1 = ss.str();

(2)利用sprintf int->char[]

(3)利用itoa int->char[]

(4)利用to_string (详见本题AC代码)

3.代码

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> s;
        for(int i=1;i<=n;i++)
           {
               if(i%15==0)
                s.push_back("FizzBuzz");
               else if(i%3==0)
                s.push_back("Fizz");
               else if(i%5==0)
                s.push_back("Buzz");
               else 
                s.push_back(to_string(i));
           }
        return s;
    }
};

  

原文地址:https://www.cnblogs.com/rgvb178/p/5964498.html