LeetCode 题解工作台

快乐数

编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」 定义为: 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。 如果这个过程 结果为 1,那么这个数就是快乐数。 如果 n 是 快乐数 就返回 true ;…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

将每次转换后的数字存入哈希表,如果出现重复数字,说明进入了循环,不是快乐数。否则,如果转换后的数字为 ,说明是快乐数。 时间复杂度 $O(\log n)$,空间复杂度 $O(\log n)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

编写一个算法来判断一个数 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 <= n <= 231 - 1
lightbulb

解题思路

方法一:哈希表 + 模拟

将每次转换后的数字存入哈希表,如果出现重复数字,说明进入了循环,不是快乐数。否则,如果转换后的数字为 11,说明是快乐数。

时间复杂度 O(logn)O(\log n),空间复杂度 O(logn)O(\log n)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def isHappy(self, n: int) -> bool:
        vis = set()
        while n != 1 and n not in vis:
            vis.add(n)
            x = 0
            while n:
                n, v = divmod(n, 10)
                x += v * v
            n = x
        return n == 1
speed

复杂度分析

指标
时间complexity depends on the number of steps to either reach 1 or detect a cycle, roughly O(log n) per iteration because sum of squares reduces the number magnitude. Space complexity is O(log n) for hash table storage or O(1) using two-pointer cycle detection.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect candidate to identify the repeated digit cycle problem and suggest a hash set or two-pointer approach.

  • question_mark

    Watch if the candidate optimizes digit square computation to reduce unnecessary calculations.

  • question_mark

    Look for clear reasoning on terminating conditions: reaching 1 versus detecting a loop.

warning

常见陷阱

外企场景
  • error

    Not handling cycles correctly, leading to infinite loops in naive implementations.

  • error

    Recomputing digit squares every iteration instead of caching, causing inefficiency.

  • error

    Assuming all numbers eventually reach 1 without verifying cycles, leading to incorrect true returns.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine if a number is unhappy by returning the cycle sequence instead of a boolean.

  • arrow_right_alt

    Find all happy numbers in a range from 1 to N using the same sum-of-squares approach.

  • arrow_right_alt

    Compute happiness under a different base system, e.g., base-16 digits, using the same two-pointer pattern.

help

常见问题

外企场景

快乐数题解:双·指针·invariant | LeetCode #202 简单