LeetCode Q 263 - Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Solution
Code: Recursive approach
public boolean isUgly(int n) {
if (n <= 0) return false;
else if (n == 1 || n == 2 || n == 3 || n == 5) return true;
else if (n % 2 == 0) return isUgly(n / 2);
else if (n % 3 == 0) return isUgly(n / 3);
else if (n % 5 == 0) return isUgly(n / 5);
else return false;
}
Code: Iterative approach
public boolean isUgly(int n) {
if (n <= 0) return false;
while (n >= 2 && n % 2 == 0) n /= 2;
while (n >= 3 && n % 3 == 0) n /= 3;
while (n >= 5 && n % 5 == 0) n /= 5;
return n == 1;
}