Understanding Happy Number
Repeatedly replace n with the sum of the squares of its decimal digits. Return whether this process reaches 1.
How it works
The digit-sum transformation forms a deterministic sequence; two speeds detect a cycle without storing every value.
Define the sum-of-squared-digits transformation. Advance slow once and fast twice until they meet. The number is happy exactly when the meeting value is 1.
Try an example
Input: n = 19
Output: true
The digit-sum transformation forms a deterministic sequence; two speeds detect a cycle without storing every value.
Constraints
- n is an integer from 1 through 1,000,000.
- Reaching a cycle that does not contain 1 returns false.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.