Problem
An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5. Given an integern, return true if n is an ugly number.
Examples
Constraints
- -2^31 <= n <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 263 with 20 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 263 # by problem number
lcpy gen -s ugly_number # by problem name
n, return true if n is an ugly number.
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
Input: n = 1
Output: true
Explanation: 1 has no prime factors.
Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.
class Solution:
# Time: O(log n)
# Space: O(1)
def is_ugly(self, n: int) -> bool:
if n <= 0:
return False
for p in (2, 3, 5):
while n % p == 0:
n //= p
return n == 1
| Time | Space |
|---|---|
| O(log n) | O(1) |