Top 150 InterviewЛегко

Happy Number

Detailed guide and Python implementation for the 'Happy Number' problem.

Постановка задачи

Легко

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

- Starting with any positive integer, replace the number by the sum of the squares of its digits.

- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

- Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Implement a function 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?
Consider using Math & Geometry-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Готовы решить?

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

Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.

Учебник по Python

Циклы Python

Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.

Посмотреть ресурс
Практическое руководство

Как генерировать случайные числа в Python

Узнайте, как генерировать случайные числа в Python. Сравните randrange, randint и генерацию равномерного числа с плавающей запятой с контролем заполнения.

Посмотреть ресурс
Шпаргалка

Шпаргалка по строковым методам Python

Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.

Посмотреть ресурс
Сравнение языков

Python против JavaScript: какой язык программирования лучше?

Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.

Посмотреть ресурс