Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- HashTable
- DP
- leetcode
- sorting
- binary tree
- string
- math
- 재귀
- list
- dfs
- linked list
- matrix
- 미디움
- easy
- two pointers
- 문자열
- backtracking
- Depth-first Search
- Array
- binary search
- 중간
- Python
- tree
- 이진트리
- Binary
- 쉬움
- Medium
- 리트코드
- recursive
- hash table
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 263(Ugly Number, Python) 본문
1. 문제 링크
Ugly Number - LeetCode
Can you solve this real interview question? Ugly Number - An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number. Example 1: Input: n = 6 Output: true Explanation: 6 =
leetcode.com
2. 문제 설명
- 주어진 숫자가 Ugly Number인지 판별하는 문제
- Ugly Number란 오직 2, 3, 5 세 소수의 곱으로만 이루어진 양의 정수
- 예시) 6, 8은 True, 14는 False, 단 1은 Ugly Number임
3. 처음 풀이
- 2로 나눠지는 만큼 모두 나누고, 3, 5도 마찬가지로 모두 나누면 1이 되어야 ugly number이다.
class Solution:
def isUgly(self, n: int) -> bool:
if n <= 0:
return False
while n % 2 == 0:
n = n // 2
if n == 1:
return True
while n % 3 == 0:
n = n // 3
if n == 1:
return True
while n % 5 == 0:
n = n // 5
if n == 1:
return True
return False
4. 다른 풀이
- 똑같은 풀이인데 while문을 3번 쓰는 것을 이렇게 간단히 쓸 수 있다.
class Solution:
def isUgly(self, n: int) -> bool:
if n==0:
return 0
for i in 2,3,5:
while n%i==0:
n//=i
return n==1
- 분자에 2, 3, 5를 충분히 많이 곱하고, 주어진 수를 분모에 넣어 나누었을 때, 2, 3, 5가 아닌 소인수가 있다면 자연수가 아닌 유리수가 됨을 이용한다.
class Solution:
def isUgly(self, n: int) -> bool:
if n<1:
return False
multiple=2*3*5
return (multiple**20)%n==0
5. 배운 점
- for 문 안에 while문을 넣을 수 있다.
- 소수 p를 약수로 갖지 않는 수를 p를 약수로 갖는 수로 나누면 정수가 되지 않는다. 이를 이용하면 편할 수 있다.
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 107(Binary Tree Level Order Traversal II, Python) (0) | 2024.02.26 |
---|---|
LeetCode 105(Construct Binary Tree from Preorder and Inorder Traversal, Python) (1) | 2024.02.24 |
LeetCode 103(Binary Tree Zigzag Level Order Traversal, Python) (0) | 2024.02.22 |
LeetCode 102(Binary Tree Level Order Traversal, Python) (0) | 2024.02.21 |
LeetCode 258(Add Digits, Python) (0) | 2024.02.20 |