Leet Code OJ 263. Ugly Number [Difficulty: Easy]

题目:
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。例如6,8是丑数,而14不是一个丑数,因为它有一个质因子7。
提示,1作为特例被认为是一个丑数。

分析:
尝试去除以2,3,5,如果可以除尽,则递归调用函数,如果都除不尽,说明这不是一个丑数。

代码:

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

你可能感兴趣的:(算法)