FizzBuzz Solution (Python)


  • 0
    S

    class Solution(object):
    def fizzBuzz(self, n):
    """
    :type n: int
    :rtype: List[str]
    """
    i = 1
    r = []

        while i <= n:            
            if i % 3 == 0 and i % 5 == 0:
                r.append('FizzBuzz')
                i+=1
                continue
            
            if i % 3 == 0:
                r.append('Fizz')
                i+=1
                continue
            
            if i % 5 == 0:
                r.append('Buzz')
                i+=1
                continue
            
            r.append(str(i))
            i+=1
        
        return r

  • 0
    R
    class Solution(object):
        def fizzBuzz(self, n):
            """
            :type n: int
            :rtype: List[str]
            """
            numlist = []
            for i in range(1, n+1):
                numlist.append(i)
            for n, i in enumerate(numlist):
                if (i % 3 == 0) & (i % 5 != 0):
                    numlist[n] = 'Fizz'
                elif (i % 5 == 0) & (i % 3 != 0):
                    numlist[n] = 'Buzz'
                elif (i % 3 != 0) & (i % 5 != 0):
                    numlist[n] = str(i)
                elif (i % 3 == 0) & (i % 5 == 0):
                    numlist[n] = 'FizzBuzz'
    
            return numlist

Log in to reply
 

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