v9.1.1
Menu

Happy Number

easyPROHash Maps & SetsApple DSA

A happy number is defined by repeatedly replacing it with the sum of squares of its digits until it either reaches 1 (happy) or loops endlessly (not happy).

Return True if n is a happy number.

Example

Input
19
Output
True
Reasoning
  • The input n is a positive integer, here 1919. Each step replaces the number with the sum of the squares of its decimal digits.
  • Starting at 1919: 12+92=1+81=821^2 + 9^2 = 1 + 81 = 82.
  • From 8282: 82+22=64+4=688^2 + 2^2 = 64 + 4 = 68. From 6868: 62+82=36+64=1006^2 + 8^2 = 36 + 64 = 100.
  • From 100100: 12+02+02=11^2 + 0^2 + 0^2 = 1. The sequence 19→82→68→100→119 \to 82 \to 68 \to 100 \to 1 reached 11, so 1919 is happy and the output is True.
  • Notice what the other ending looks like: for n=2n = 2 the sequence runs 2→4→16→37→58→89→145→42→20→42 \to 4 \to 16 \to 37 \to 58 \to 89 \to 145 \to 42 \to 20 \to 4, landing back on a value it already produced, so it repeats forever without touching 11 and the answer is False.
  • The input 11 is already 11, so it counts as happy with zero steps.

Constraints

  • 1 <= n <= 2^31 - 1

More from Apple DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.