Skip to content# FizzBuzz code challenge

### Problem

### Example

### Solution

### Appendix

## Newsletter

— 1 min read

My approach to solving LeetCode’s FizzBuzz code challenge.

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`

(as a string) if none of the above conditions are true.

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

We start by creating a new temporary array (`temp`

). Then we initialise for loop where we do have three checks to do during each iteration and push the result into the `temp`

array.

- If the number is divisible by
`3`

and not`5`

. - If the number is divisible by
`5`

and not by`3`

. - If the number is divisible by
`15`

. - If none of the above works, we return the current iterable and convert it as a string using the template literals.

Finally, we return the `temp`

array.

```
1var fizzBuzz = function (n) {2 const temp = [];3
4 for (let i = 1; i <= n; i++) {5 if (i % 3 === 0 && i % 5 !== 0) {6 temp.push('Fizz');7 } else if (i % 5 === 0 && i % 3 !== 0) {8 temp.push('Buzz');9 } else if (i % 15 === 0) {10 temp.push('FizzBuzz');11 } else {12 temp.push(`${i}`);13 }14 }15
16 return temp;17};
```

Sign up to get updates when I write something new. No spam ever.

Subscribe to my Newsletter