Math Number tricks

89. Happy Number

Easy

You are given a positive integer n. One step replaces the number with the sum of the squares of its digits. For example, one step turns 203 into 2² + 0² + 3² = 13.

Start from n and take steps, again and again. n is happy if the numbers reach 1 at some point. Return true if n is happy and false if it is not.

1 itself is happy, since it is already 1. In C++, Java, Go, Rust and C#, n is a 64-bit integer.

Example 1

Input: n = 7

Output: true

Explanation: The steps go 7 → 49 → 97 → 130 → 10 → 1.

Example 2

Input: n = 2

Output: false

Explanation: The steps go 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. The numbers are back at 4, so from here they repeat the same eight numbers forever and never reach 1.

Example 3

Input: n = 1000000000000000

Output: true

Explanation: The digits are a 1 and fifteen 0s, so one step gives 1² = 1.

Check your understanding

Work out the answer for this input before you write any code.

n = 1112

Constraints

  • 1 ≤ n ≤ 1015

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.