LeetCode 263: Ugly Number Solution
Master LeetCode problem 263 (Ugly Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
263. Ugly Number
Problem Explanation
Explanation
To determine if a number is ugly, we repeatedly divide it by 2, 3, and 5 as long as it is divisible by any of these numbers. If the final result is 1, then the original number is ugly. Otherwise, it is not ugly. We can implement this approach in a loop and return true if n equals 1 at the end.
- Time complexity: O(log n) - where n is the input number
- Space complexity: O(1)
Solution Code
class Solution {
public boolean isUgly(int n) {
if (n <= 0) return false;
for (int i = 2; i < 6 && n > 0; i++) {
while (n % i == 0) {
n /= i;
}
}
return n == 1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 263 (Ugly Number)?
This page provides optimized solutions for LeetCode problem 263 (Ugly Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 263 (Ugly Number)?
The time complexity for LeetCode 263 (Ugly Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 263 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 263 in Java, C++, or Python.