KatInterview

263. Ugly Number

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

An ugly number is a positive integer whose prime factors are exclusively 2, 3, and 5. This means an ugly number n can be expressed as n = 2^a * 3^b * 5^c, where a, b, c are non-negative integers. The problem asks us to determine if a given integer n is an ugly number.

Solution

Ugly Number in Python

class Solution:
    def isUgly(self, n: int) -> bool:
        # Ugly numbers must be positive.
        if n <= 0:
            return False
        
        # List of prime factors for ugly numbers.
        factors = [2, 3, 5]
        
        # Repeatedly divide n by these factors.
        for factor in factors:
            while n % factor == 0:
                n //= factor
        
        # If n is reduced to 1, it's an ugly number.
        return n == 1

Ugly Number in Java

class Solution {
    public boolean isUgly(int n) {
        // Ugly numbers must be positive.
        if (n <= 0) {
            return false;
        }

        // An array of prime factors for ugly numbers.
        int[] factors = {2, 3, 5};
        
        // Repeatedly divide n by these factors.
        for (int factor : factors) {
            while (n % factor == 0) {
                n /= factor;
            }
        }
        
        // If n is reduced to 1, it's an ugly number.
        return n == 1;
    }
}

Ugly Number in C++

class Solution {
public:
    bool isUgly(int n) {
        // Ugly numbers must be positive.
        if (n <= 0) {
            return false;
        }

        // Define the prime factors for ugly numbers.
        int factors[] = {2, 3, 5};

        // Repeatedly divide n by these factors.
        for (int factor : factors) {
            while (n % factor == 0) {
                n /= factor;
            }
        }

        // If n is reduced to 1, it's an ugly number.
        return n == 1;
    }
};

Ugly Number in TypeScript

function isUgly(n: number): boolean {
    // Ugly numbers must be positive.
    if (n <= 0) {
        return false;
    }

    // An array of prime factors for ugly numbers.
    const factors: number[] = [2, 3, 5];

    // Repeatedly divide n by these factors.
    for (const factor of factors) {
        while (n % factor === 0) {
            n /= factor;
        }
    }

    // If n is reduced to 1, it's an ugly number.
    return n === 1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.