Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Which means an ugly number is 2^i * 3^j * 5^k * 1 (i,j,k are non-negative integers).
Therefore, we can keep dividing the given number with 2, 3, 5 until its not dividable by 2,3,5.
Then we can determine it is an ugly number if the remaining is equal to 1.
public class Solution {
public boolean isUgly(int num) {
if (num <= 0) return false;
while (num%2==0) num /= 2;
while (num%3==0) num /= 3;
while (num%5==0) num /= 5;
return num == 1;
}
}
转载请注明原文地址: https://ju.6miu.com/read-812.html