Java easy iterative solution


  • 16
    S
    public class Solution {
        public List<String> fizzBuzz(int n) {
            List<String> list = new ArrayList<>();
            for (int i = 1; i <= n; i++) {
                if (i % 3 == 0 && i % 5 == 0) {
                    list.add("FizzBuzz");
                } else if (i % 3 == 0) {
                    list.add("Fizz");
                } else if (i % 5 == 0) {
                    list.add("Buzz");
                } else {
                    list.add(String.valueOf(i));
                }
            }
            return list;
        }
    }
    

  • 5

    not that there is really anything to this problem but I favor your approach for that exact reason, just write the code like the problem states, no combining cases. For something this simple best to go with the most readable solution. Anyhow, just my 2 cents!


  • 1
    K

    @songzec Integer.toString(int i) is better


  • 0
    S

    @kw2012 Can you tell me why?


  • 0
    L

    What if n == 2?


  • 1
    C

    For the first if condition, we can let i % 15.


  • 0
    X
    This post is deleted!

  • 1
    A

    @songzec String.valueOf(int i) just call the Integer.toString(int i);

        /**
         * Returns the string representation of the {@code int} argument.
         * <p>
         * The representation is exactly the one returned by the
         * {@code Integer.toString} method of one argument.
         *
         * @param   i   an {@code int}.
         * @return  a string representation of the {@code int} argument.
         * @see     java.lang.Integer#toString(int, int)
         */
        public static String valueOf(int i) {
            return Integer.toString(i);
        }
    

  • 0
    L

    @kw2012 I think they are same.

       public static String valueOf(int i) {
            return Integer.toString(i);
        }
    

Log in to reply
 

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