Skip to content
Decoder

Happy Number

Easy

Problem

Start with a positive integer n and repeatedly replace it with the sum of the squares of its digits. If this process reaches 1, the number is *happy*. Otherwise it loops forever in a cycle that never includes 1. Return true if n is happy.

Example 1

Input
n = 19
Output
true
Why
1 + 81 = 82, 64 + 4 = 68, 36 + 64 = 100, 1 + 0 + 0 = 1

Example 2

Input
n = 2
Output
false
Why
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ...

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.