Skip to content

Instantly share code, notes, and snippets.

@petergi
Created January 8, 2024 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petergi/1c3feaccafd90a60f8f2cef3d3f2aad0 to your computer and use it in GitHub Desktop.
Save petergi/1c3feaccafd90a60f8f2cef3d3f2aad0 to your computer and use it in GitHub Desktop.
By preallocating the ArrayList with the initial capacity of n, we avoid resizing the list during the loop, which improves performance. Instead of using multiple conditional statements, used StringBuilder to build the result string. Additionally, used sb.length() == 0 to check if the StringBuilder is empty, instead of using multiple else if state…
/**
* Generates a list of strings based on the given integer input.
*
* @param n the maximum integer value to generate strings for
* @return a list of strings containing the generated values
*/
public List<String> fizzBuzz(int n) {
List<String> res = new ArrayList<>(n)
for (int i = 1; i <= n; i++) {
StringBuilder sb = new StringBuilder()
if (i % 3 == 0) {
sb.append("Fizz")
}
if (i % 5 == 0) {
sb.append("Buzz")
}
if (sb.length() == 0) {
sb.append(i)
}
res.add(sb.toString())
}
return res
}
@petergi
Copy link
Author

petergi commented Jan 8, 2024

I hate FizzBuzz questions. Dumb Question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment