【Leetcode】263. Ugly Number

class Solution1(object):
    def isUgly(self, num):
        """
        If curr num has factor of 2 or 3 or 5, we divide it and finally the result whether 1 or not
        """
        if num <= 1 :return False
        while(num % 2 == 0):
            num //= 2
        while(num % 3 == 0):
            num //= 3
        while(num % 5 == 0):
            num //= 5
        return num == 1

class Solution2(object):
    """
    use dynamic programming to solve this question
    we can use the number smaller than current number to judge
    if current number could exactly divide 2 and current number // 2 meet the conditions , the current number also match
    but following solution will cause memory error when num is too large
    """
    def isUgly(self, num):
        if num <= 1 : return num == 1
        dp = [False]*(num+1)
        dp[1] = True
        for i in range(2,num+1):
            if i % 2 == 0: dp[i] = dp[i] or dp[i // 2]
            if i % 3 == 0: dp[i] = dp[i] or dp[i // 3]
            if i % 5 == 0: dp[i] = dp[i] or dp[i // 5]
        return dp[-1]


class Solution3(object):
    """
    I try to use dictionary to take place of array but also memory error
    """
    def isUgly(self, num):
        if num <= 1 : return num == 1
        dict = {1: True}
        for i in range(2,num+1):
            if i % 2 == 0 and dict[i//2] \
                    or i % 3 == 0 and dict[i//3]\
                    or i % 5 == 0 and dict[i//5]:
                dict[i] = True
            else:
                dict[i] = False
        return dict[num]

相关文章: