Description
Solution 1(C++)
class Solution {
public:
bool isUgly(int num) {
if(num <= 9) return num==0 || num==7 || num < 0? false: true;
if(num %2 == 0) return isUgly(num/2) ? true: false;
else if(num %3 == 0) return isUgly(num/3) ? true: false;
else if(num %5 == 0) return isUgly(num/5) ? true: false;
return false;
}
};
Solution 2(C++)
class Solution {
public:
bool isUgly(int num) {
if(num == 0) return false;
while(num%2 == 0) num/=2;
while(num%3 == 0) num/=3;
while(num%5 == 0) num/=5;
return num == 1;
}
};
算法分析
解法一: 解法一采用的迭代的方法可以参考: LeetCode-326. Power of Three、
LeetCode-21. Merge Two Sorted Lists、 LeetCode-784. Letter Case Permutation。
解法二: 这种方法其实暗含了求一个数的因数的方法。而且这个方法无需额外考虑负数情况。挺好的,简洁大气。
程序分析
略。