leetcode(263,389) python实现

题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)

结果如下:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值