263. Ugly Number
Ugly Number
An ugly number is a positive integer whose prime factors are limited to 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, therefore all of its prime factors are limited to 2, 3, and 5.
Example 3:
Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7.
Constraints:
-231 <= n <= 231 - 1
var isUgly = function (n) {
if(n <= 0) return false
while (n != 1) {
if (n % 2 === 0) {
n /= 2
} else if (n % 3 === 0) {
n /= 3
} else if (n % 5 === 0) {
n /= 5
} else {
return false
}
}
return true
};
/**
* @param {number} n
* @return {boolean}
*/
const isUgly = (n) => {
// Handle all non positive nos
if(n <= 0) return false;
// Anything below 5 is ugly
if(n <= 5) return true;
// Start dividing recursively
for(const divider of [2, 3, 5]) {
if(n % divider === 0) {
return isUgly(n / divider);
}
}
return false;
};
That’s all folks! In this post, we solved LeetCode problem 263. Ugly Number
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment