263. Ugly Number LeetCode Solution

In this guide, you will get 263. Ugly Number LeetCode Solution with the best time and space complexity. The solution to Ugly Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Ugly Number solution in C++
  4. Ugly Number solution in Java
  5. Ugly Number solution in Python
  6. Additional Resources
263. Ugly NumberLeetCode Solution image

Problem Statement of Ugly Number

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:

-231 <= n <= 231 – 1

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

263. Ugly Number LeetCode Solution in C++

class Solution {
 public:
  bool isUgly(int n) {
    if (n == 0)
      return false;

    for (const int prime : {2, 3, 5})
      while (n % prime == 0)
        n /= prime;

    return n == 1;
  }
};
/* code provided by PROGIEZ */

263. Ugly Number LeetCode Solution in Java

class Solution {
  public boolean isUgly(int n) {
    if (n == 0)
      return false;

    for (final int prime : new int[] {2, 3, 5})
      while (n % prime == 0)
        n /= prime;

    return n == 1;
  }
}
// code provided by PROGIEZ

263. Ugly Number LeetCode Solution in Python

class Solution:
  def isUgly(self, n: int) -> bool:
    if n == 0:
      return False

    for prime in 2, 3, 5:
      while n % prime == 0:
        n //= prime

    return n == 1
 # code by PROGIEZ

Additional Resources

See also  198. House Robber LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.