1. Topic
Write A program this outputs the string representation of numbers from 1 to N.
Multiples of three it should output "Fizz" instead of the number and for the multiples of the five output "Buzz". For numbers which is multiples of both three and five output "Fizzbuzz".
Given a number n, it is required to write a string representing 1 to n, where the output "Fizz" divisible by 3, the output "Buzz" divisible by 5, and the output "Fizzbuzz" divisible by 3 and 5.
2. Ideas
The idea is very simple. It is the individual who should be able to do it. But there are a few things you can learn, one is the application of vectors in C + + (as you can see from this article), and the other is the method of int to string in C + +.
Here are some ideas for int to string:
(1) Using StringStream:
When using StringStream, be careful to add # include "Sstream". For example, if I want to convert 23 of int to string, then I can do this:
int a=23; StringStream SS; ss<<a; string S1 = Ss.str ();
(2) using sprintf int->char[]
(3) using Itoa int->char[]
(4) using to_string (refer to the AC code)
3. Code
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; };
LeetCode-412. Fizz Buzz-(c + +)-Problem Solving report