Java clean solution using StringBuilder and only if-statements


  • 1
    G

    Here is my solution, easy to read and doesn't require to have an extra if-statement to handle numbers that are multiples of both three and five individually.

    public class Solution {
        public List<String> fizzBuzz(int n) {
            List<String> result = new ArrayList<>();
            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);
                result.add(sb.toString());
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.