Solution by StanSilas


  • 0
    S

    Introduction

    alt text

    QUESTION:
    We are given a number n, and we have to output the numbers from 1 to n , with the followin exceptions, if number is divisible by 3, that number should be replaced by Fizz, if that number is divisible by 5 that number should be replaced by Buzz, and if the number is divisible by both 3 & 5, we have to replace that number by FizzBuzz.

    Keypoints :
    The expected return type is a List of strings. So if n = 1, and you return an int [1] , it is wrong , it has to be ["1"].
    A number N is divisible by another number M , if N%M is 0. % is the modulus. N%M returns the remainder.

    Conditions :
    N% 3 == 0
    N%5 == 0
    N%5 and N%3 == 0
    N%5 and N%3 != 0

    Return type :
    List[str]

    Tips :
    convert int to string before appending.

    APPROACH:
    Save Fizz , Buzz and FizzBuzz as strings to three variables
    First check if the number is not divisible by both 3 and 5, and if that is the case convert our i to a str and append it to our list.

    Then check remaining conditions.

    SOLUTION:

        def fizzBuzz(self, n):
            """
            :type n: int
            :rtype: List[str]
            """
            my_list =[]
            a = "Fizz"
            b = "Buzz"
            c = "FizzBuzz"
            for i in range(1,n+1):
                k=str(i)
                if i%3!=0 and i%5!=0:
                    my_list.append(k)
                elif i%5==0 and i%3==0:
                    my_list.append(c)
                elif i%3==0:
                    my_list.append(a)
                elif i%5==0:
                    my_list.append(b)
                
            return my_list ```
    
    A simple and straightforward solution.
    
    FizzBuzz is supposed to be a very famous question that is used to frequently separate non programmers from programmers. 
    
    Approach 2: 
    
    Conclusion :
    ![alt text](http://wwwcdn.printmag.com/wp-content/uploads/APPYFIZZ_2016_10_new-600x371.jpg)
    
    Appy fizz is a very popular drink in India.

Log in to reply
 

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