EasyNo. 0263
Ugly Number — LeetCode 263 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Math
- Reading time
- 2 min
- Source
- leetcode.com
The problem
An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5. Given an integer n, return true if n is an ugly number.
Example
- Input
- n = 6
- Output
- true
- Explanation
- 6 = 2 × 3
Python solution
class Solution:
def isUgly(self, n: int) -> bool:
if n < 1:
return False
for x in [2, 3, 5]:
while n % x == 0:
n //= x
return n == 1Complexity
- Time
- O(n) or O(1)
- Space · auxiliary
- O(1)
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 263. Ugly Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0264 | Ugly Number II | Medium |
| 1201 | Ugly Number III | Medium |
| 0258 | Add Digits | Easy |
| 0273 | Integer to English Words | Hard |
| 0002 | Add Two Numbers | Medium |
| 0007 | Reverse Integer | Medium |
Frequently asked questions
- How hard is LeetCode 263. Ugly Number?
LeetCode 263. Ugly Number is rated Easy on LeetCode.
- What topics does LeetCode 263. Ugly Number cover?
LeetCode 263. Ugly Number is tagged Math on LeetCode.