Leetcode 202 快乐数


Leetcode 202 快乐数

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」 定义为:

  • 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
  • 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
  • 如果这个过程 结果为 1,那么这个数就是快乐数。

如果 n快乐数 就返回 true ;不是,则返回 false

示例 1:

复制代码
输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

示例 2:

复制代码
输入:n = 2
输出:false

提示:

  • 1 &lt;= n &lt;= 2<sup>31</sup><span> </span>- 1

Solution


第一反应,这不就是模运算吗。果断写下:

python 复制代码
class Solution:
    def isHappy(self, n: int) -> bool:
        if n == 1: return True
        res = 0
        while n >= 10:
            res += (n%10)**2 
            n = n % 10
        return self.isHappy(res)

然后果断报错。

RecursionError: maximum recursion depth exceeded

分析一下,这是对于无限循环的情况缺少考虑。

无限循环的情况是什么呢?就是检测之前是否出现过。毕竟是循环。所以如果之前出现过的数集。

python 复制代码
class Solution:
    def __init__(self) -> None:
        self.visited = set()
  
    def isHappy(self, n: int) -> bool:
        if n == 1: return True
      
        if n in self.visited:return False
        self.visited.add(n)
        res = 0
        while n >= 10:
            res += (n%10)**2 
            n = n % 10
        return self.isHappy(res)

但是:

python 复制代码
class Solution:
    def __init__(self) -> None:
        self.visited = set()
  
    def isHappy(self, n: int) -> bool:
        if n == 1: return True
      
        if n in self.visited:return False
        self.visited.add(n)
        res = 0
        while n >= 10:
            res += (n%10)**2 
            n = n % 10
        return self.isHappy(res)
python 复制代码
✓ 2 tests complete
× @test(7)  result: false ,expect: true

这次的问题出在哪里呢?

原代码中的 while n >= 10 条件会导致个位数被忽略。例如,对于数字 19,代码会计算 9^2 = 81,但会忽略 1^2。

python 复制代码
class Solution:
    def __init__(self) -> None:
        self.visited = set()
  
    def isHappy(self, n: int) -> bool:
        if n == 1: return True
    
        if n in self.visited:return False
        self.visited.add(n)
        res = 0
        while n > 0:
            res += (n%10)**2 
            n = n // 10
        return self.isHappy(res)

ok, 通过。

相关推荐
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
颜酱1 天前
单调栈:从模板到实战
javascript·后端·算法
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
CoovallyAIHub1 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉