[LeetCode] Ugly Number

时间:2023-03-08 17:38:11

Ugly Number

Total Accepted: 20760 Total Submissions: 63208 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.

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

class Solution {
public:
bool isUgly(int num) {
if (num == || num == || num == || num == ) return true;
vector<int> u = {,,};
for (int i = ; i < u.size(); i++) {
if (num % u[i] == ) {
int p = num / u[i];
if (p == || p == || p == || !isPrime(p) && isUgly(p)) return true;
}
}
return false;
} bool isPrime(int num) {
for (int i = ; i*i <= num; i++) {
if (num % i == ) return false;
}
return true;
}
};

这题花了一番功夫,主要卡在质因数分解上。我的思路是用2,3,5去整除num,如果结果不是2,3,5而且不是其他任何质数的话,它就是ugly的。但是这个思路有个问题,以28为例子,用2除的得14,因此14不是2,3,5中的一个同时也不是质数,所以被判为了ugly。但事实是14还可以被分解为2 x 7, 而7 是质数,因此7 也是28的一个质因子,因此28不是ugly数,怎么办呢,灵机一抖的我想到如果再保证除2,3,5以后的数是ugly的不就解决了。。。所以我在超长的if 语句后面加上isUgly的递归调用,结果证明这个思路是正确的 Accepted.