Algorithm
Problem Name: 263. 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
Code Examples
#1 Code Example with C Programming
Code -
C Programming
bool isUgly(int num) {
int pf[] = { 2, 3, 5 };
int i = sizeof(pf) / sizeof(pf[0]);
while (num && -- i >= 0) {
while (!(num % pf[i])) {
num = num / pf[i];
//printf("%d, ", num);
}
}
return num == 1 ? true : false;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
bool isUgly(int num) {
return num ? !(num%2) ? isUgly(num/2) : !(num%3) ? isUgly(num/3) : !(num%5) ? isUgly(num/5) : num == 1 : false;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public boolean isUgly(int n) {
int[] primes = {2, 3, 5};
for (int i = 0; i < primes.length; i++) {
while (n > 1 && n % primes[i] == 0) {
n /= primes[i];
}
}
return n == 1;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const isUgly = function(num) {
if (num < 1) return false
while (num >= 2) {
if (num % 2 === 0) num = num / 2
else if (num % 3 === 0) num = num / 3
else if (num % 5 === 0) num = num / 5
else return false
}
return true
}
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
while num>1:
if num%2!=0 and num%3!=0 and num%5!=0: return False
else: num/=[i for i in (2,3,5) if num%i==0][-1]
return num==1
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0263_UglyNumber
{
public bool IsUgly(int num)
{
if (num <= 0) return false;
while (num > 1 && (num % 2 == 0))
num /= 2;
while (num > 1 && (num % 3 == 0))
num /= 3;
while (num > 1 && (num % 5 == 0))
num /= 5;
return num == 1;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output