Happy Number

25 min · isHappy()

A number can chase its own digits into one of two endings: it reaches 1, or it gets trapped revisiting the same values forever.

Given a positive integer n, repeatedly replace it with the sum of the squares of its digits. Return true if this process eventually reaches 1; otherwise return false.

A number that reaches 1 is called happy. Once a value repeats, every value after it must repeat too, so the process can never escape to 1.

A few ground rules:

  • Use every decimal digit, including zeros inside the number.
  • Stop as soon as you reach 1 or prove that the values are repeating.
  • The input is always a positive signed 32-bit integer—a whole number within -2^31 through 2^31 - 1.

Constraints

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

Hints

Write the transformation first

Pop one digit with remainder % 10, square it, and add it to a running sum. Then discard that digit with integer division by 10.

How do you prove forever?

There are only finitely many values the process can visit after its first step. If you keep a set of values you've already seen, a repeat proves you're in a loop.

Can two runners expose the loop?

Move one value through one transformation at a time and another through two. If there's a loop, the faster one must eventually catch the slower one.

Follow-up

Can you detect the repeating loop without storing every value you've visited?

Visible cases

Examples

Example 1

ready
Input
n = 19
Expected
true
Why
19 reaches 1 after following its digit-square sums

Example 2

ready
Input
n = 2
Expected
false
Why
2 eventually enters a repeating cycle that excludes 1

Example 3

ready
Input
n = 1
Expected
true
Why
1 has already reached the happy ending

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite