Fizz Buzz Problem


Description

LeetCode Problem 412.

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == “FizzBuzz” if i is divisible by 3 and 5.
  • answer[i] == “Fizz” if i is divisible by 3.
  • answer[i] == “Buzz” if i is divisible by 5.
  • answer[i] == i if non of the above conditions are true.

Example 1:

1
2
Input: n = 3
Output: ["1","2","Fizz"]

Example 2:

1
2
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 3:

1
2
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

Constraints:

  • 1 <= n <= 10^4


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> res(n);
        for(int i = 1; i <= n; i++) {
            res[i - 1] = to_string(i);
        }
        for(int i = 2; i < n; i += 3) {
            res[i] = "Fizz";
        }
        for(int i = 4; i < n; i += 5) {
            res[i] = "Buzz";
        }
        for(int i = 14; i < n; i += 15) {
            res[i] = "FizzBuzz";
        }
        return res;
    }
};




Related Posts

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...