DEV Community

Cover image for 412. Fizz Buzz | LeetCode in C#
junian
junian

Posted on • Originally published at junian.net on

412. Fizz Buzz | LeetCode in C#

The Fizz Buzz problem is a classic exercise that is often used to teach basic programming concepts such as loops and conditionals.

In this article, I'll show you my attempt to solve this problem.

Intuition

When breaking down the problem, the task is to iterate through a sequence of numbers while applying simple divisibility rules to determine the correct output for each number.

The logic is straightforward: replace numbers with specific words based on their divisibility.

Approach

To solve the Fizz Buzz problem, we can use a simple loop and a series of conditional checks:

  1. Initialize a List: Start by creating a list to store the results.
  2. Iterate through Numbers: Loop through numbers from 1 to n.
  3. Check Divisibility:
    • If a number is divisible by both 3 and 5, it should be labeled "FizzBuzz".
    • Else, if it's divisible by 3, label it "Fizz".
    • Else, if it's divisible by 5, label it "Buzz".
    • If none of these conditions are met, add the number itself as a string.
  4. Add to List: For each number, append the appropriate label or number to the results list.
  5. Return the Result: Finally, return the list containing all the strings.

Complexity

  • Time complexity: The time complexity is O(n) because we process each number from 1 to n exactly once.

  • Space complexity: The space complexity is O(n) because we store a string result for each number in the

Code

public class Solution {
    public IList<string> FizzBuzz(int n) {
        var result = new List<string>{};
        for(var i = 1; i <= n; i++)
        {
            if(i % 3 == 0 && i % 5 == 0)
            {
                result.Add("FizzBuzz");
            }
            else if(i % 3 == 0)
            {
                result.Add("Fizz");
            }
            else if(i % 5 == 0)
            {
                result.Add("Buzz");
            }
            else
            {
                result.Add(i.ToString());
            }
        }
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Video

Conclusion

This approach provides an efficient way to implement the Fizz Buzz logic by using a loop and conditional checks.

The function generates the desired output for any valid positive integer n, allowing it to handle a wide range of input values effectively.

This solution is not only concise but also clear, making it easy to understand for anyone familiar with basic programming constructs.

This explanation captures the essence of how the Fizz Buzz problem can be addressed programmatically with a simple and clean loop-and-conditional structure.

References

Top comments (0)