Created
January 8, 2024 01:31
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hate FizzBuzz questions. Dumb Question.