Home > Java > javaTutorial > . Fizz Buzz

. Fizz Buzz

Susan Sarandon
Release: 2024-11-06 11:55:03
Original
1069 people have browsed it

. 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;
    }
}

Copy after login

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;
}
}


Copy after login

The above is the detailed content of . Fizz Buzz. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template