Java solution w/o StringBuilder or String variable, or w/o modulo


  • 0
    Y
        public List<String> fizzBuzz(int n) {
            List<String> res = new ArrayList<>();
    
            for (int i = 1; i <=n; i++) {
                if (i % 15 == 0)
                    res.add("FizzBuzz");
                else if (i % 3 == 0)
                    res.add("Fizz");
                else if (i % 5 == 0)
                    res.add("Buzz");
                else
                    res.add("" + i);
            }
            return res;
        }
    

    Another solution w/o modulo:

        public List<String> fizzBuzz(int n) {
            String[] str = new String[n];
            
            
            for (int i = 3; i <=n; i += 3)
                str[i - 1] = "Fizz";
    
            for (int i = 5; i <=n; i += 5)
                if (str[i - 1] == null)
                    str[i - 1] = "Buzz";
                else
                    str[i - 1] += "Buzz";
    
            for (int i = 1; i <= n; i++) {
                if (str[i - 1] == null)
                    str[i - 1] = ("" + i);
            }
    
            return Arrays.asList(str);
        }
    

Log in to reply
 

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