263. Ugly Number [easy] (Python)

来源:互联网 发布:手机淘宝怎么用集分宝 编辑:程序博客网 时间:2024/06/15 21:23

题目链接

https://leetcode.com/problems/ugly-number/

题目原文

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.

题目翻译

编程判断一个给定的数是否是“ugly number”。

所谓“ugly number”是指质因数仅包含在 2,3,5 中的正数。比如,6和8都是“ugly number”,而14不是,因为14包含7这个质因数。

注意,1 也被认为是”ugly number”。

思路方法

思路一

根据定义,依次将所给的数除以 2,3,5 直至无法除尽,如果这时得到1则说明所给的数的质因子不超出2,3,5三个数,否则说明有其他质因数。

代码一

class Solution(object):    def isUgly(self, num):        """        :type num: int        :rtype: bool        """        if num <= 0:            return False        for i in [2, 3, 5]:            while num%i == 0:                num = num / i        return True if num == 1 else False

思路不变,该题不用迭代法而用递归也可以实现。

代码二

class Solution(object):    def isUgly(self, num):        """        :type num: int        :rtype: bool        """        if num <= 0:            return False        if num == 1:            return True        if num % 2 == 0:            return self.isUgly(num/2)        elif num % 3 == 0:            return self.isUgly(num/3)        elif num % 5 == 0:            return self.isUgly(num/5)        else:            return False

思路二

考虑到输入是int,python对于大整数的处理非常方便,可以用非常短的代码解决该问题。
对于一个 int 型的 ugly number, x=2m3n5t,由于 x<2147483647,故m<31,n<20,t<14
所以一定有,若 y=2a3b5c,且a>=30,b>=19,c>=13,则 y%x=0

代码

class Solution(object):    def isUgly(self, num):        """        :type num: int        :rtype: bool        """        return num > 0 == 30**30 % num

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51317748

0 0