爱程序网

[LeetCode] Ugly Number (A New Question Added Today)

来源: 阅读:

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.

 

     这是今天才加上去的新题。没啥可说的。只要把ugly number的定义搞清楚就可以很好的写了。

     因为prime factor只能为2,3,5。所以只要一个数不能被分解为只含有这三个数的乘式那么它就不是一个ugly number了。

     代码如下。~

public class Solution {
    public boolean isUgly(int num) {
        if(num<=0){
            return false;
        }
        if(num==1){
            return true;
        }
        while(num!=1){
            if(num%2==0){
                num=num/2;
            }else if(num%3==0){
                num=num/3;
            }else if(num%5==0){
                num=num/5;
            }else{
                return false;
            }
        }
        return true;
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助