gpt4 book ai didi

Java FizzBu​​zz 1 行

转载 作者:行者123 更新时间:2023-12-01 17:43:23 25 4
gpt4 key购买 nike

如何完成FizzBuzz 在 Codingbat 中仅使用 return 语句进行练习?

我上次用来解决问题的代码是:

public String[] fizzBuzz(int start, int end) {
String[] a = new String[end - start];
for(int i = start; i < end; i++) a[i - start] = i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : String.valueOf(i);
return a;
}

我的目标是让代码看起来像这样:

public String[] fizzBuzz(int start, int end) {
return foo;
}
<小时/>

问题

This is slightly more difficult version of the famous FizzBuzz problem which is sometimes given as a first problem for job interviews. (See also: FizzBuzz Code.) Consider the series of numbers beginning at start and running up to but not including end, so for example start=1 and end=5 gives the series 1, 2, 3, 4. Return a new String[] array containing the string form of these numbers, except for multiples of 3, use "Fizz" instead of the number, for multiples of 5 use "Buzz", and for multiples of both 3 and 5 use "FizzBuzz". In Java, String.valueOf(xxx) will make the String form of an int or other type. This version is a little more complicated than the usual version since you have to allocate and index into an array instead of just printing, and we vary the start/end instead of just always doing 1..100.

<小时/>

测试用例

fizzBuzz(1, 6) → ["1", "2", "Fizz", "4", "Buzz"]
fizzBuzz(1, 8) → ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7"]
fizzBuzz(1, 11) → ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz"]
fizzBuzz(1, 16) → ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
fizzBuzz(1, 4) → ["1", "2", "Fizz"]
fizzBuzz(1, 2) → ["1"]
fizzBuzz(50, 56) → ["Buzz", "Fizz", "52", "53", "Fizz", "Buzz"]
fizzBuzz(15, 17) → ["FizzBuzz", "16"]
fizzBuzz(30, 36) → ["FizzBuzz", "31", "32", "Fizz", "34", "Buzz"]
fizzBuzz(1000, 1006) → ["Buzz", "1001", "Fizz", "1003", "1004", "FizzBuzz"]
fizzBuzz(99, 102) → ["Fizz", "Buzz", "101"]
fizzBuzz(14, 20) → ["14", "FizzBuzz", "16", "17", "Fizz", "19"]

最佳答案

不确定为什么要在单个 return 语句中执行此操作,但仍然是这样:

return IntStream.range(start, end)
.mapToObj(i -> i % 15 == 0 ? "FizzBuzz" :
i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : String.valueOf(i))
.toArray(String[]::new);
  1. IntStream.range返回连续有序的 IntStream来自start (含)至end (独家)增量步骤 1,这完全符合您的命令式方法的方式。
  2. mapToObj使我们能够转换 IntStreamStream<String> .
  3. toArray使我们能够转换 Stream<String>String[]返回。

您可以阅读有关 IntStream 的更多信息API here .

关于Java FizzBu​​zz 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58259733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com