Easy-题目19: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. 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的正整数。特殊地,1是丑陋数。
题目分析:
直观地,用2,3,5分别试除这个数,若可以整除直至得到1,则该数是丑陋数。
源码:(language:java)

public class Solution {
    public boolean isUgly(int num) {
        if(num==0)
            return false;

        while(num!=1)   {
            if(num%2==0)
                num/=2;
            else if(num%3==0)
                num/=3;
            else if(num%5==0)
                num/=5;
            else
                return false;
        }

        return true;
    }
}

成绩:
2ms,beats 18.00%,众数2ms,82.00%
Cmershen的碎碎念:
此题显然有递归解法,因为n是丑数等价于n/2,n/3,n/5中有一个是丑数。但是提交递归解法会超时。

你可能感兴趣的:(Easy-题目19:263. Ugly Number)