Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

412. Fizz Buzz

If you are given an integer n, find the Fizz Buzz representation of each integer from 1 to n, and return the result with an array of strings (subscript starting from 1) :

  • Answer [I] == “FizzBuzz” if I is a multiple of 3 and 5.
  • Answer [I] == “Fizz” if I is a multiple of 3.
  • Answer [I] == “Buzz” if I is a multiple of 5.
  • Answer [I] == I If none of the above conditions are met.

 

Example 1: Input: n = 3 Output: ["1","2","Fizz"] Example 2: Input: n = 5 Output: ["1","2","Fizz","4","Buzz"] Example 3: Input: n = 15 Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]Copy the code

Their thinking

Answer [I] answer[I] answer[I] answer[I] answer[I] answer[I] answer[I] answer[I] Answer [I] contains both “Fizz” and” Fuzz”, and “Fizz” precedes” Buzz”.

Iterate over [1…n] to see if I satisfies the requirement that it be a multiple of 3 and 5 at the same time. Output “FizzBuzz”. If I is a multiple of 3, print “Fizz”. If I is a multiple of 5, print “Buzz”. Otherwise print I

code

class Solution {
    public List<String> fizzBuzz(int n) {

        List<String> res=new ArrayList<>();
        
        for(int i=1; i<=n; i++) {if(i%3= =0&&i%5= =0)
            {
                res.add("FizzBuzz");
            }else if(i%3= =0){
                res.add("Fizz");
            }else if(i%5= =0)
            {
                res.add("Buzz");
            }else res.add(""+i);
            
        }
        returnres; }}Copy the code
    public List<String> fizzBuzz(int n) {

        List<String> res=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);
             res.add(sb.toString());
        }
        return res;
    }
Copy the code
  • Time complexity: O(n). Each integer from 1 to n needs to be traversed. For each integer I, the time complexity of generating answer[I] is O(1).

  • Space complexity: O(1). Note that the returned value does not count space complexity