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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。