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

Validate IP Address Problem

LeetCode 468. Given a string queryIP, return “IPv4” if IP...

Strong Password Checker Problem

LeetCode 420. A password is considered strong if the below...

Find The Closest Palindrome Problem

LeetCode 564. Given a string n representing an integer, return...

Student Attendance Record I Problem

LeetCode 551. You are given a string s representing an...

Repeated Substring Pattern Problem

LeetCode 459. Given a string s, check if it can...

Remove K Digits Problem

LeetCode 402. Given string num representing a non-negative integer num,...