Skip to main content

Ugly Number

LeetCode 263 | Difficulty: Easy​

Easy

Problem Description​

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

Input: n = 6
Output: true
Explanation: 6 = 2 Γ— 3

Example 2:

Input: n = 1
Output: true
Explanation: 1 has no prime factors.

Example 3:

Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.

Constraints:

- `-2^31 <= n <= 2^31 - 1`

Topics: Math


Approach​

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.


Solutions​

Solution 1: C# (Best: 52 ms)​

MetricValue
Runtime52 ms
MemoryN/A
Date2018-04-12
Solution
public class Solution {
public bool IsUgly(int num) {
if(num==1) return true;
if(num==0) return false;
while (num % 2 == 0) num /= 2;
while (num % 3 == 0) num /= 3;
while (num % 5 == 0) num /= 5;
return num==1;
}
}

Complexity Analysis​

ApproachTimeSpace
Solution$O(n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.