首页 > 其他 > 详细

263. Ugly Number

时间:2021-04-10 16:09:20      阅读:17      评论:0      收藏:0      [点我收藏+]

思路:
如果一个数为丑数,那么自然会被2,3,5整除,最后得到1,那么我们一直循环判断n是否能被2,3,5其中一个整除,如果能 那么n=n/(2 or 3 or 5)。如果三个数都不能整除那么就返回false。如果循环结束还没有返回false,那么就直接返回true。
代码:

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

下面是递归写法

class Solution {
public:
    bool isUgly(int n) {
        bool res;
        if(n==0) return false;
        if(n==1) return true;
        if(n%2==0) res=isUgly(n/2);
        else if(n%3==0) res=isUgly(n/3);
        else if(n%5==0) res=isUgly(n/5);
        else return false;
        return res;
    }
};

263. Ugly Number

原文:https://www.cnblogs.com/Mrsdwang/p/14640477.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!