Skip to main content
Back to problems
Leetcode
Medium
Math
Sets
Bit Manipulation
Happy Number

Determine whether repeatedly replacing a number with the sum of the squares of its digits eventually reaches 1.

Acceptance 0%
Problem Statement

Happy Number

Given a positive integer n, repeatedly transform it by replacing the number with the sum of the squares of its decimal digits.

A number is called happy if this process eventually reaches 1. If the process enters a cycle that does not include 1, the number is unhappy.

Return whether the given number is happy.

Input Format

  • A single integer n.
  • You may assume n > 0.

Output Format

  • Return true if n is a happy number.
  • Otherwise, return false.

Constraints

  • 1 <= n
  • The number may be transformed repeatedly until it reaches 1 or a cycle is detected.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 19

Output

true

Explanation

19 -> 12+91^{2}+9^2 = 82 -> 82+28^{2}+2^2 = 68 -> 12+81^{2}+8^2 = 65 -> 61 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 ... The process eventually reaches a cycle that does not include 1, so 19 is not happy? Wait, this example should be the classic happy-number example. Correct sequence: 19 -> 82 -> 68 -> 100 -> 1. The number 19 is happy.

Example 2

Input

n = 2

Output

false

Explanation

2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 ... The sequence repeats without reaching 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.