Ugly Number leetcode java

问题描述:

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.

分析:一个数,因式分解后,素数因子若只包含2/3/5,称为是ugly number;否则,不是ugly number。

        给定一个数,判定它是不是ugly number。

算法:注意将 <=0的数过滤掉

    /**
     * 判断一个数是不是ugly number
     * @param num
     * @return
     */
    
    //将num除去2,3,5这三个因子后,应该得到最终结果为1,若不为1,就不是ugly number
    public static boolean isUgly(int num) {
       if(num <= 0) //题目要求是整数,所以对于非整数一定要进行排除,否则会超时
           return false;
       while(num % 2 == 0)//如果存在2的质因子,则将所有2都找出来
           num = num / 2;
       while(num % 3 == 0)//接着找出所有的3
           num = num / 3;
       while(num % 5 == 0)//找出所有的5
           num = num / 5;
       return (num == 1) ;//若除了2,3,5之外,不存在其他质数因子,则为ugly number
 
    }
原文地址:https://www.cnblogs.com/mydesky2012/p/5035815.html