150强访谈简单

快乐数

“快乐数字”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个算法来确定数字 n 是否快乐。

快乐数是由以下过程定义的数:

- 从任何正整数开始,将数字替换为其数字的平方和。

- 重复该过程,直到数字等于 1(它将停留在该位置),或者在不包含 1 的循环中无限循环。

- 此过程以 1 结尾的数字是快乐的。

如果 n 是一个快乐的数字,则返回 true,否则返回 false。

实现函数 isHappy(n: int) -> bool

约束条件
  • 1 <= n <= 2^31 - 1

示例

Example 1
Input
19
Output
True
Explanation

1^2 + 9^2 = 82. 8^2 + 2^2 = 68. 6^2 + 8^2 = 100. 1^2 + 0^2 + 0^2 = 1. Since we reached 1, 19 is a happy number.

Example 2
Input
2
Output
False
Explanation

2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> ... This loops forever without reaching 1.

Need a Hint?
考虑使用数学和几何特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。