首页  >  文章  >  Java  >  。嘶嘶声

。嘶嘶声

Susan Sarandon
Susan Sarandon原创
2024-11-06 11:55:031042浏览

. Fizz Buzz

问题

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

解决方案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;
    }
}

解决方案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;
}
}


以上是。嘶嘶声的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn