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
- Problem Statement
- Complexity Analysis
- Ugly Number solution in C++
- Ugly Number solution in Java
- Ugly Number solution in Python
- Additional Resources

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
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.