263. 丑数

263. 丑数

给你一个整数 n ,请你判断 n 是否为 丑数 。如果是,返回 true ;否则,返回 false 。

丑数 就是只包含质因数 2、3 和/或 5 的正整数。

示例 1:

输入:n = 6
输出:true
解释:6 = 2 × 3

迭代(或递归)

  • 迭代的比较简单,就是对该数字依次持续整除2,3,5,直至无法再除。
  • 所谓持续整除是指若当前的n % 2 == 0,则进行n /= 2的操作
class Solution {
public:
    bool isUgly(int n) {
        if(n == 1)
            return true;
        else if(n <= 0)
            return false;
        
        while(!(n % 2))
            n /= 2;
        while(!(n % 3))
            n /= 3;
        while(!(n % 5))
            n /= 5;

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

递归

  • 递归思想和迭代一样,只是重复去调用原函数
class Solution {
public:
    bool isUgly(int n) {
        if(n == 1)
            return true;
        else if(n <= 0)
            return false;

        if(n % 2 == 0)
            return isUgly(n/2);
        if(n % 3 == 0)
            return isUgly(n/3);
        if(n % 5 == 0)
            return isUgly(n/5);
        
        return false;
    }
};
posted @ 2021-04-21 12:01  andymori  阅读(104)  评论(0)    收藏  举报