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,ugly number的定义是:该数字的素因数(就是那种身上没有一点肉了,再瘦不下来了的数字)如果是【2,3,5】之外的数字,那么不是ugly,否则是ugly,比如14的素因数有2,7,那么就不是ugly了,12的素因数是:2,3,就是ugly啦
或者简写成这样的
class Solution(object): def isUgly(self, num): for p in 2, 3, 5: while num % p == 0 < num: num /= p return num == 1再来一个递归版本的,这个效率达到了这里面的最高92.03%
#1.如果这个数小于1,返回,否#2.让该数依次对【2,3,5】取余数#如果为0,把该数重新赋值,递归回去class Solution(object): def isUgly(self, num): if (num <= 0):return False; if (num == 1):return True; if num%2==0: return self.isUgly(num/2) if num%3==0: return self.isUgly(num/3) if num%5==0: return self.isUgly(num/5) return False新闻热点
疑难解答