Ugly Number — LeetCode 263 Python Solution

EasyMath
Problem
#263
Reading time
2 min

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 == 1

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview