Happy Number

easy
math
hashmap

A number is happy if the following process ends at 1: replace the number with the sum of the squares of its digits, then repeat. A number is not happy if the process loops endlessly without ever reaching 1.

Return true if n is happy and false otherwise.

Input / output

  • Input: n: integer (positive)
  • Output: true if n is happy, else false

Examples

  1. n = 19 returns true (1^2+9^2=82, 8^2+2^2=68, 6^2+8^2=100, 1^2+0^2+0^2=1).
  2. n = 2 returns false (it enters the cycle 4, 16, 37, 58, 89, 145, 42, 20, 4, ...).
  3. n = 1 returns true.

Constraints

  • 1 <= n <= 2,147,483,647

Follow-up The digit-square process eventually cycles. Can you detect the cycle with Floyd's slow/fast pointers in O(1) extra space instead of a seen set?

Examples

Example 1

Input: n = 19
Output: true

Example 2

Input: n = 2
Output: false

Example 3

Input: n = 1
Output: true
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.