Every day a leetcode
题目来源:263. 丑数
解法1:数学
丑数 就是只包含质因数 2、3 和 5 的正整数。
根据提示 -231 <= n <= 231 - 1,特判:
- n<=0,不是丑数
- n == 1,是丑数
将n依次被5、3、2整除,最后判断n是否为1。
代码:
/*
* @lc app=leetcode.cn id=263 lang=cpp
*
* [263] 丑数
*/
// @lc code=start
class Solution
{
public:
bool isUgly(int n)
{
if (n <= 0)
return false;
if (n == 1)
return true;
while (n % 5 == 0)
n /= 5;
while (n % 3 == 0)
n /= 3;
while (n % 2 == 0)
n /= 2;
return n == 1;
}
};
// @lc code=end
递归写法:
/*
* @lc app=leetcode.cn id=263 lang=cpp
*
* [263] 丑数
*/
// @lc code=start
class Solution
{
public:
bool isUgly(int n)
{
if (n <= 0)
return false;
if (n == 1)
return true;
if (n % 5 == 0)
return isUgly(n / 5);
if (n % 3 == 0)
return isUgly(n / 3);
if (n % 2 == 0)
return isUgly(n / 2);
return n == 1;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(logn),时间复杂度取决于对n除以2、3、5的次数, 由于每次至少将n除以2,因此除法运算的次数不会超过O(logn)。
空间复杂度:O(1)