//GitHub https://github.com/vellimole0621
vellimole0621 - Overview
キム・ヒョンギュ . vellimole0621 has 6 repositories available. Follow their code on GitHub.
github.com
412. Fizz Buzz
https://leetcode.com/problems/fizz-buzz/
Fizz Buzz - LeetCode
Can you solve this real interview question? Fizz Buzz - Given an integer n, return a string array answer (1-indexed) where: * answer[i] == "FizzBuzz" if i is divisible by 3 and 5. * answer[i] == "Fizz" if i is divisible by 3. * answer[i] == "Buzz" if i is
leetcode.com
문제 설명
:
Given an integer n, return a string array answer (1-indexed) where:
- answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
- answer[i] == "Fizz" if i is divisible by 3.
- answer[i] == "Buzz" if i is divisible by 5.
- answer[i] == i (as a string) if none of the above conditions are true.
=> 1부터 n까지 3의 배수, 5의 배수, 3의 배수이면서 5의 배수인 수 를 각각 판단하는 문제.
내 풀이
:
n까지 반복문으로, 15의 배수 & 5의 배수 & 3의 배수 & 셋 다 아닌 경우를 구분해서, 배열에 추가했다.
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
answer = []
for i in range(1, n+1):
if i % 15 == 0:
answer.append("FizzBuzz")
elif i % 5 == 0 and i % 15 != 0:
answer.append("Buzz")
elif i % 3 == 0 and i % 15 != 0:
answer.append("Fizz")
else:
answer.append(f"{i}")
return answer
더 나은 풀이(leetcode 참조)
:
3의 배수이면서 5의 배수(= 15의 배수)를 나와 달리 3의 배수 안에 다시 조건문을 둠으로써, 연산 과정을 줄였다.
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
answer = list(range(1,n+1))
for i in answer:
if i % 3 == 0:
if i % 5 == 0:
answer[i-1] = 'FizzBuzz'
else:
answer[i-1] = 'Fizz'
elif i % 5 == 0:
answer[i-1] = 'Buzz'
else:
answer[i-1] = str(i)
return answer
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Ransom Note (0) | 2023.08.01 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Number of Steps to Reduce a Number to Zero (0) | 2023.07.31 |
[파이썬 Python/알고리즘] LeetCode - Richest Customer Wealth (0) | 2023.07.30 |
[파이썬 Python/알고리즘] LeetCode - Integer to Roman (0) | 2023.07.29 |
[파이썬 Python/알고리즘] LeetCode - Valid Perfect Square (0) | 2023.07.19 |