Ugly Number — LeetCode 263 Python Solution
EasyMath
- Problem
- #263
- Pattern
- Math and Number Theory
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
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
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.