Buckle 9. Fizz Buzz problem
https://www.lintcode.com/problem/fizz-buzz/description
Gives you an integer n . From 1 to n , print each number according to the following rules:
- If the number is evenly divided by 3, print
fizz
. - If the number is evenly divided by 5, print it
buzz
. - If the number is divisible by
3
and at the same time5
, printfizz buzz
. - If the number is neither
3
divisible nor5
divisible, print the number本身。
Idea: if classification
#include "stdafx.h"
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
/**
* @param n: An integer
* @return: A list of strings.
*/
vector<string> fizzBuzz(int n)
{
// write your code here
vector<string>result;
for (int i = 1; i <= n; i++)
{
if (i%15==0)
{
result.push_back("fizz buzz");
}
else if (i % 3 == 0)
{
result.push_back("fizz");
}
else if (i % 5 == 0)
{
result.push_back("buzz");
}
else
{
result.push_back(to_string(i));
}
}
return result;
}
};
int main()
{
Solution s;
auto result = s.fizzBuzz(15);
return 0;
}
int and string conversion
One, to_string function
The c ++ 11 standard adds the global function std :: to_string:
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Second, with the help of string stream
The standard library defines three types of string streams: istringstream, ostringstream, stringstream. Looking at the name, you know that these types are very similar to the ones in iostream. You can read, write, and read and write string types. They are indeed Derived from the iostream type. To use them, you need to include the sstream header file.
In addition to the operations inherited from iostream
1. The sstream type defines a constructor with string parameters, namely: stringstream stream (s); creates a stringstream object that stores a copy of s, where s is a string type object
2. A member named str is defined to read or set the string value manipulated by the stringstream object: stream.str (); returns the string type object stream.str (s) stored in stream; converts the string type s Copy to stream, return void
int aa = 30;
string s1;
stringstream ss;
ss<<aa;
ss>>s1;
cout<<s1<<endl; // 30