您的位置:首页 > 编程语言 > Python开发

leetcode(263,389) python实现

2017-11-10 20:33 351 查看

题263

题目要求判断一个数是否是丑数,丑数定义为它的质因数只包括在2,3,5。

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以外的素数肯定不是丑数,如果能够整除2,3,5中的数,就更新num,让num除以2,3,5,重复以上步骤,直到不能整除为止,如果最后num=1,则为丑数。

代码如下:

class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""

if num<=0:
return False

while True:
if num % 2 == 0:
num=num/2
continue
if num % 3==0:
num=num/3
continue
if  num % 5 ==0:
num=num/5
continue
if  num==1:
return True
else:
return False
s=Solution()
print(s.isUgly(6))


结果如下:



题389

题目要求:给定两个数组,寻找两个数组中不一样的元素。具体如下:

题目比较简单,看t中那个元素s中没有,就添加这个元素到res,容易出现的问题是s和t中有一个同样的元素,但是数量不一样,此时要判断两个元素的出现的次数,然后输出多余的该元素。

代码如下:

class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res=''
for i in t:
if i not in s:
res+=i
else:
if s.count(i) != t.count(i) and i not in res:
res+=i
return res

r = Solution()
s='abcd'
t='abcde'
res=r.findTheDifference(s,t)
print(res)


结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python