Ugly Number
LeetCode 263 | Difficulty: Easyβ
EasyProblem 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)β
| Metric | Value |
|---|---|
| Runtime | 52 ms |
| Memory | N/A |
| Date | 2018-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β
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.