Ugly Number Problem
#263
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 263.
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 = 2 × 3
Example 2:
Input: n = 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.
Example 4:
Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
- -2^31 <= n <= 2^31 - 1
Solution
Approach: Divide Out 2, 3 and 5
A positive number is ugly exactly when nothing is left after removing all of its factors 2, 3 and 5.
- If
n <= 0, returnfalse: ugly numbers are positive by definition. This check also matters for the loop below, since0 % 2 == 0forever. - While
nis divisible by 2, divide it by 2. Do the same for 3, then for 5. - Return whether what remains is 1.
If n had any other prime factor (7, 11, ...), dividing by 2, 3 and 5 never removes it, so the remainder is greater than 1. For n = 1, nothing is divided and the answer is true, as in Example 4.
Complexity: O(log n) time, since every division at least halves n. O(1) space.
class Solution:
def isUgly(self, n: int) -> bool:
if n <= 0:
return False # ugly numbers are positive
# Remove every factor 2, 3 and 5; an ugly number has nothing else left.
for factor in (2, 3, 5):
while n % factor == 0:
n //= factor
return n == 1
Now write it from memory
Close the write-up and solve it yourself against the tests.