263. Ugly Number

来源:互联网 发布:urlencoder编码 js 编辑:程序博客网 时间:2024/05/11 19:31

题目

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.


思路

判断数能否被2,3,5整除,不能返回false,能的话做除法再递归,直到值为1为止


代码

class Solution {public:    bool canBeUglyNum(int &num)    {        int numFlag[3] = {2,3,5};        for(int i=0;i<sizeof(numFlag)/sizeof(int);i++)        {            if(num % numFlag[i] == 0)            {                num /= numFlag[i];                return true;            }        }        return false;    }    bool isUgly(int num) {        if(num < 1)        {            return false;        }        while(num > 1)        {            if(!canBeUglyNum(num))            {                return false;            }        }        return true;    }};
0 0