LeetCode-412. Fizz Buzz-(c + +)-Problem Solving report

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.