Search⌘ K
AI Features

Happy Number

Explore how to determine if a number is a happy number by applying the fast and slow pointer pattern. Understand the process of summing the squares of digits and detecting cycles to decide if a number leads to 1 or loops indefinitely.

Statement

Write an algorithm to determine if a number nn is a happy number.

We use the following process to check if a given number is a happy number:

  • Starting with the given number nn, replace the number with the sum of the squares of its digits.
  • Repeat the process until:
    • The number equals 11, which will depict that the given number nn is a happy number.
    • The number enters a cycle, which will depict that the given number nn is not a happy number.

Return TRUE if nn is a happy number, and FALSE if not.

Constraints

  • 11 \leq nn 2311\leq 2^{31} - 1

Examples

canvasAnimation-image
1 / 2

Test your understanding of the problem

Let’s take a moment to make sure we have correctly understood the problem. The quiz below helps us to check that we are solving precisely the right problem:

Happy Number

1.

(True or False) 28 is a happy number.

A.

True

B.

False


1 / 2

Figure it out

We have a game for you to play: re-arrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to re-arrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

Java
usercode > Main.java
import java.util.*;
public class Main{
public static boolean isHappyNumber(int n) {
// Replace this placeholder return statement with your code
return false;
}
}
Happy Number