首页 > 学院 > 开发设计 > 正文

20170307-leetcode-263-Ugly Number

2019-11-06 06:14:19
字体:
来源:转载
供稿:网友

1.Description

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啦

2.Solution

#1.如果这个数小于1,返回,否#2.让该数依次对【2,3,5】取余数#如果为0,把该数重新赋值,中间定义一个#标志,如果该标志不发生变化,说明前后#两次的值不再发生变化,返回false,如果最后结果为1,返回trueclass Solution(object): def isUgly(self, num): if num<1:return False while 1: flag = 0 for prime in [2, 3, 5]: if num % prime == 0: flag = 1 num = num/prime if num == 1: return True if flag == 0: return False

或者简写成这样的

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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表