Write a function that returns the string representation of all numbers from 1 to n based on the following rules:
• If it's a multiple of 3, represent it as "fizz".
• If it's a multiple of 5, represent it as "buzz".
• If it's a multiple of both 3 and 5, represent it as "fizzbuzz".
• If it's neither, just return the number itself.
Example
function fizzBuzz(num){
}
input:15
output:'12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz'.
Solution
function fizzBuzz(num) {
let i = 1;
let result = "";
while (i <= num) {
if (i % 15 === 0) {
result += "fizzbuzz";
} else if (i % 3 === 0) {
result += "fizz";
} else if (i % 5 === 0) {
result += "buzz";
} else {
result += i;
}
i++;
}
return result;
}
const result = fizzBuzz(15)
console.log(result); // '12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz'
Top comments (0)