Skip to content
Advertisement

Java FizzBuzz 1 Line

How can one complete the FizzBuzz exercise in Codingbat with just a return statement?

The code that I last used to solve the problem was:

JavaScript

My goal is to have code that looks something like this:

JavaScript

Problem

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.


Test Cases

JavaScript

Advertisement

Answer

The only way that I could imagine without any Java 8 features involves some ugly conversions of arrays to strings, and strings of arrays of strings to arrays of strings with some very … pragmatic regular expressions. But I guess the solution is not supposed to be pretty anyhow. It passes all the test cases, though, so it achieves all the goals that can be achieved with test-driven development…

Never write anything even remotely resembling this in real life!

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement