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. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

质数(prime number)又称素数,有无限个。除了1和它本身以外不再有其他的除数整除。根据算术基本定理,每一个比1大的整数,要么本身是一个质数,要么可以写成一系列质数的乘积,最小的质数是2。

丑数的定义就是它的质因数只有2,3和5,也就是一个丑数是N个2、N个3 和 N个5的乘积。

public class Solution {
    public boolean isUgly(int num) {
        if(num == 0) return false;
        if(num == 1) return true;
        int n = num;
        while(n%2 == 0){
            n /= 2;
        }

        while(n%3 == 0){
            n /= 3;
        }

        while(n%5 == 0){
            n /= 5;
        }

        return n == 1 ? true : false;
    }
}

你可能感兴趣的:(Ugly Number)