• 【Python3】【力扣题】202. 快乐数


    【力扣题】题目描述:

    【Python3】代码:

    1、解题思路:用哈希集合检测循环。设置集合记录每次结果,判断结果是否为1。若计算结果已在集合中则进入循环,结果一定不为1。

    (1-1)知识点:集合:元素不重复的序列,大括号“{}”,元素之间逗号“,”隔开。

                               str(...):转为字符串。为了遍历每一个数字。

                               int(...):转为整数。为了进行数学运算。

                               sum(...):求和。

                               集合.add(...):往集合中添加元素。

    1. class Solution:
    2. def isHappy(self, n: int) -> bool:
    3. res = {n} # 将最初的n加入集合
    4. while n != 1:
    5. n = sum(int(x)**2 for x in str(n)) # 每一位数字的平方再求和
    6. if n in res: return False
    7. else: res.add(n)
    8. return True

    (1-2)知识点:set( ):创建空集合。

                               map(函数,序列):序列映射。序列中每一个元素调用函数执行操作,返回新序列。

    注解:此处的 return n==1 相当于 if n==1:return True; else: return False

    1. class Solution:
    2. def isHappy(self, n: int) -> bool:
    3. res = set() # 创建空集合
    4. while n != 1 and n not in res:
    5. res.add(n)
    6. n = sum(map(lambda x:int(x)**2,str(n))) # 每一位数字的平方再求和
    7. return n == 1

    (1-3)知识点:n % 10:十进制的数字获取最低位。

                               n // 10:十进制的数字去除最低位,相当于右移。

    1. class Solution:
    2. def isHappy(self, n: int) -> bool:
    3. # 计算每一位的数字的平方再求和,返回计算结果
    4. def get_next(n):
    5. total = 0
    6. while n > 0:
    7. total += (n % 10) ** 2
    8. n //= 10
    9. return total
    10. # 判断是否为1
    11. res = set()
    12. while n != 1:
    13. res.add(n)
    14. n = get_next(n)
    15. if n in res: return False
    16. return True

    2、解题思路:快慢指针。慢指针计算一次,快指针计算两次,判断是否为1。若快指针和慢指针相同且不为1,则进入循环,结果一定不为1。

    注解:slow,fast = n,get_next(n) 相当于 slow=n;fast=get_next(n)。

    1. class Solution:
    2. def isHappy(self, n: int) -> bool:
    3. # 计算每一位的数字的平方再求和,返回计算结果
    4. def get_next(n):
    5. total = 0
    6. while n > 0:
    7. total += (n % 10) ** 2
    8. n //= 10
    9. return total
    10. slow,fast = n,get_next(n)
    11. while slow != fast:
    12. slow = get_next(slow)
    13. fast = get_next(get_next(fast))
    14. return fast == 1

    3、解题思路:数学。大量求解得出的数学规律,结果不为1的循环为4→16→37→58→89→145→42→20→4。因此只要计算结果在这个循环中,一定不为1。

    1. class Solution:
    2. def isHappy(self, n: int) -> bool:
    3. cycle_num = {4,16,37,58,89,145,42,20} # 集合
    4. while n not in cycle_num:
    5. n = sum(map(lambda x:int(x)**2,str(n))) # 每一位数字的平方再求和
    6. if n == 1: return True
    7. return False

     

  • 相关阅读:
    Linux文件与文件系统的压缩
    读高性能MySQL(第4版)笔记20_Performance Schema和其他
    计算机网络概述
    520. 检测大写字母
    洪荒学院 发布全球十大机器人大脑 纵然智障依然有其优劣!
    【WinForm】关于截图识别数字并计算的桌面程序实现方案
    [一篇读懂]C语言三讲:选择、循环
    上海亚商投顾:沪指创反弹新高 房地产板块掀涨停潮
    TDK | CeraLink 电容器快速切换逆变器的革新
    2023最新SSM计算机毕业设计选题大全(附源码+LW)之java高校心理健康咨询平台vknhv
  • 原文地址:https://blog.csdn.net/yannan20190313/article/details/134088770