412: Time 97.26%, Solution with step by step explanation
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Create an empty list called ans to store the resulting strings.\n2. Lo
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create an empty list called ans to store the resulting strings.\n2. Loop through the range of integers from 1 to n (inclusive), using the range function.\n3. Check if the current number is divisible by 3 by using the modulus operator %. If the remainder is 0, then the number is divisible by 3, and we set a boolean variable divisible_by_3 to True.\n4. Check if the current number is divisible by 5 by using the modulus operator %. If the remainder is 0, then the number is divisible by 5, and we set a boolean variable divisible_by_5 to True.\n5. If the number is divisible by both 3 and 5, then append the string "FizzBuzz" to the ans list.\n6. If the number is only divisible by 3, then append the string "Fizz" to the ans list.\n7. If the number is only divisible by 5, then append the string "Buzz" to the ans list.\n8. If the number is not divisible by either 3 or 5, then append the string representation of the number to the ans list using the str function.\n9. After the loop is finished, return the ans list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n    def fizzBuzz(self, n: int) -> List[str]:\n        ans = []\n        for i in range(1, n+1):\n            divisible_by_3 = (i % 3 == 0)\n            divisible_by_5 = (i % 5 == 0)\n            \n            if divisible_by_3 and divisible_by_5:\n                ans.append("FizzBuzz")\n            elif divisible_by_3:\n                ans.append("Fizz")\n            elif divisible_by_5:\n                ans.append("Buzz")\n            else:\n                ans.append(str(i))\n        \n        return ans\n\n```
['Math', 'String', 'Simulation', 'Python', 'Python3']