Advertisement

Ugly Number - LeetCode 263 Solution

Ugly Number - Complete Solution Guide

Ugly Number is LeetCode problem 263, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 &times; 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

Detailed Explanation

The problem asks you to determine if a given integer `n` is an 'ugly number'. An ugly number is a positive integer whose only prime factors are 2, 3, or 5. The input is an integer `n`, and the output is a boolean value: `true` if `n` is an ugly number, and `false` otherwise. The input integer can be positive, negative, or zero.

Solution Approach

The solution uses a straightforward approach. It first checks if the input `n` is less than or equal to 0. If so, it immediately returns `false` because ugly numbers must be positive. Otherwise, it iteratively divides `n` by 2, 3, and 5 as long as it's divisible. After this process, if `n` is equal to 1, it means that all prime factors were 2, 3, or 5, thus the number is ugly; otherwise, it's not. This is done using `while` loops for efficiency.

Step-by-Step Algorithm

  1. Step 1: Check if `n` is less than or equal to 0. If true, return `false`.
  2. Step 2: Divide `n` by 2 repeatedly until it's no longer divisible by 2.
  3. Step 3: Divide `n` by 3 repeatedly until it's no longer divisible by 3.
  4. Step 4: Divide `n` by 5 repeatedly until it's no longer divisible by 5.
  5. Step 5: Check if `n` is equal to 1. If true, return `true`; otherwise, return `false`.

Key Insights

  • Insight 1: Repeatedly dividing by 2, 3, and 5: The core idea is to repeatedly divide the input number by 2, 3, and 5 until it's no longer divisible by any of them. If the final result is 1, it means the original number only had 2, 3, and 5 as prime factors.
  • Insight 2: Handling negative and zero inputs: The problem explicitly states that an ugly number is a *positive* integer. Therefore, negative numbers and zero are not ugly numbers and should be handled separately.
  • Insight 3: Efficiency of the while loops: The `while` loops are efficient because they continue dividing until the number is no longer divisible by the prime factor. This avoids unnecessary iterations.

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(1)

Topics

This problem involves: Math.

Companies

Asked at: J.P. Morgan.