878217. Fizz Buzz
Easy
Fizz Buzz
Slug: fizz-buzz
Difficulty: Easy
Id: 878217
Topic Tags: Strings, Arrays
Company Tags: None
Summary
The Fizz Buzz problem is a classic algorithmic challenge that involves printing numbers from 1 to n, but with certain conditions. If the number is divisible by both 3 and 5, print "FizzBuzz". If it's only divisible by 3, print "Fizz". If it's only divisible by 5, print "Buzz". Otherwise, just print the number.
Detailed Explanation
The approach to this problem involves a simple loop that iterates from 1 to n. Within the loop, we check the current number against these conditions:
- If the number is divisible by both 3 and 5 (i.e.,
n % (3 * 5) == 0), print "FizzBuzz". - If the number is only divisible by 3 (
n % 3 == 0butn % 5 != 0), print "Fizz". - If the number is only divisible by 5 (
n % 5 == 0butn % 3 != 0), print "Buzz". - Otherwise, just print the number.
Here's a step-by-step breakdown of the solution:
for (int i = 1; i <= n; i++) {
if (i % (3 * 5) == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0 && i % 5 != 0) {
System.out.println("Fizz");
} else if (i % 5 == 0 && i % 3 != 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
Time complexity: O(n) Space complexity: O(1)
Optimized Solutions
Java
for (int i = 1; i <= n; i++) {
if (i % (3 * 5) == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0 && i % 5 != 0) {
System.out.println("Fizz");
} else if (i % 5 == 0 && i % 3 != 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}