[LeetCode] Ugly Number 醜陋數

weixin_34391854發表於2015-08-19

 

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.

 

這道題讓我們檢測一個數是否為醜陋數,所謂醜陋數就是其質數因子只能是2,3,5。那麼最直接的辦法就是不停的除以這些質數,如果剩餘的數字是1的話就是醜陋數了,有兩種寫法,如下所示:

 

解法一:

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

 

解法二:

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;
    }
};

 

類似題目:

Super Ugly Number

Ugly Number II

 

參考資料:

https://leetcode.com/discuss/60914/my-2ms-java-solution

https://leetcode.com/discuss/52703/2-4-lines-every-language

https://leetcode.com/discuss/78281/4ms-recursive-solution-in-c

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章