Show problems as
Classic problem #202EasyHash TableMathTwo PointersFloyd's Cycle Finding Algorithm

Happy Number

Real-world version: Probe Reading Settles
Tracked in this browser only
Read Happy Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A field probe stores one positive integer reading and runs a self-test on it.

On each tick of the self-test the firmware throws away the stored value and writes back a new one: take every decimal digit of the old value, square each digit, and add those squares together.

The probe declares itself healthy as soon as the stored value becomes 1, because 1 maps to itself and the value can never move again. For every other starting value that never lands on 1, the firmware walks around a fixed ring of values and keeps circling it forever.

Given the starting value reading, return true when the self-test eventually declares the probe healthy, and false when the firmware circles forever.

Examples

Example 1

Input
reading = 7
Output
true

The stored value moves 7 -> 49 -> 97 -> 130 -> 10 -> 1, so the probe declares itself healthy on the fifth tick.

Example 2

Input
reading = 4
Output
false

The value walks 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 and is back where it began, so it will circle that ring forever.

Example 3

Input
reading = 1000
Output
true

Only one digit is non-zero, so the very first tick stores 1 and the probe is healthy immediately.

Constraints

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

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def reading_settles(reading: int) -> bool:
Java
public boolean readingSettles(int reading)