Forem

Cover image for 412. Fizz Buzz
Mohammad Shariful Islam
Mohammad Shariful Islam

Posted on

412. Fizz Buzz

Problem

https://leetcode.com/problems/fizz-buzz/description/

Solution 01

class Solution {
    public List<String> fizzBuzz(int n) {

        List<String> ans = new ArrayList<>(n);

        for (int i = 1; i <= n; i++) {

            String text = "";

            if (i % 3 == 0 && i % 5 == 0) {
                text += "FizzBuzz";

                System.out.print("FizzBuzz");
            } else if (i % 3 == 0) {
                text += "Fizz";
                System.out.print("Fizz");
            } else if (i % 5 == 0) {
                text += "Buzz";

                System.out.print("Buzz");
            } else {
                text += String.valueOf(i);
                System.out.print(i);
            }

            ans.add(text);
        };
        return ans;
    }
}

Enter fullscreen mode Exit fullscreen mode

Solution 02

class Solution {
public List<String> fizzBuzz (int n) {

List<String> answer = new ArrayList<>(n);

for (int i = 1; i <= n; i++) {

boolean divisibleBy3 = 1 % 3 == 0;
boolean divisibleBy5 = 1 % 5 == 0;

if (divisibleBy3 && divisibleBy5){

 answer.add("FizzBuzz");

} else if (divisibleBy3) {

 answer.add("Fizz");

} else if (divisibleBy5) { 

answer.add("Buzz");

} else {

answer.add(String.valueOf(i)); }
}
            return answer;
}
}


Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay