Happy Number in Java
Check whether a number is a happy number.
- Time
O(log n) for the first step, then a small fixed amount of work - Space
O(1) in practice, because the set stays small - Hints3
- Read2 min
A happy number reaches 1 when you keep replacing it with the sum of the squares of its digits. For example, 19 goes to 82, 68, 100 and then 1. Numbers that are not happy never reach 1. They end up in an endless loop that always contains 4.
Problem statement
Write a program to check a happy number in Java. Take a positive number, add the
squares of its digits, and repeat with the result. If you reach 1, it is happy. If the
values start to repeat without reaching 1, it is not.
An integer n.
true if n is happy, otherwise false.
Examples
n = 19true1 + 81 = 82, 64 + 4 = 68, 36 + 64 = 100, 1 + 0 + 0 = 1.
n = 20false20 goes to 4, 16, 37, 58, 89, 145, 42 and then 20 again.
Constraints
- 1 <= n <= 2^31 - 1
Think before you code
Reveal the questions to ask yourself first
- How do you get the digits of a number one at a time?
- How will the program know it is going in circles?
- What is the answer for 1?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- If
nis 0 or negative, return false. - While
nis not 1:- If
nwas seen before, return false. - Remember
n, then replace it with the sum of its squared digits.
- If
- Return true.
Splitting a number into digits is the same trick used to
find the sum of the digits. The set is
a HashSet, whose add returns false for a repeat.
Dry run
Walk through the example step by step
Happy number in Java example with 19:
n | squared digits | next n
----+-----------------+-------
19 | 1 + 81 | 82
82 | 64 + 4 | 68
68 | 36 + 64 | 100
100 | 1 + 0 + 0 | 1
1 | stop | happy
Solution
Reveal the full Java solution
import java.util.HashSet;
import java.util.Set;
public class HappyNumber {
static int sumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
public static boolean isHappy(int n) {
if (n <= 0) {
return false;
}
Set<Integer> seen = new HashSet<>();
while (n != 1) {
if (!seen.add(n)) {
return false; // value came back: endless loop
}
n = sumOfSquares(n);
}
return true;
}
public static void main(String[] args) {
System.out.println(isHappy(19)); // true
System.out.println(isHappy(20)); // false
System.out.println(isHappy(1)); // true
}
}This is the happy number in Java using while loop. The set guarantees that the loop
stops: an int has at most 10 digits, so after one step the value is at most
10 * 81 = 810. From then on it must reach 1 or repeat.
Happy number in Java using for loop
This version needs no set. It uses the known fact that every number that is not happy reaches 4.
static boolean isHappyFor(int n) {
if (n <= 0) return false;
for (; n != 1 && n != 4; ) {
int sum = 0;
for (int x = n; x > 0; x /= 10) {
sum += (x % 10) * (x % 10);
}
n = sum;
}
return n == 1;
}
Happy number in Java using recursion
The same idea, using sumOfSquares from the main solution. The method calls itself with
the next value until it meets 1 or 4.
static boolean isHappyRecursive(int n) {
if (n == 1) return true;
if (n <= 0 || n == 4) return false;
return isHappyRecursive(sumOfSquares(n));
}
All three gave the same answer for every number from 1 to 99,999 when we ran them.
Print happy numbers from 1 to 50
for (int i = 1; i <= 50; i++) {
if (isHappy(i)) System.out.print(i + " ");
}
// 1 7 10 13 19 23 28 31 32 44 49
After this happy number in Java program, try the magic number, the digital root and more Java coding questions. For guided practice, see the Java full stack course.
O(log n) for the first step, then a small fixed amount of workO(1) in practice, because the set stays smallReview before the interview
Common mistakes
- Looping until n is 1 with no repeat check. It never ends for numbers like 20.
- Adding the digits instead of their squares.
- Stopping with false at any single digit. 7 is a single digit and is happy.
Edge cases to test
- 1 is happy.
- 7 is happy: 49, 97, 130, 10, 1.
- 0 and negative numbers are not happy.
Interview follow-ups
- How would you detect the loop with slow and fast pointers and no set?
- How would you print the first n happy numbers?
- Why can the value never be more than 810 after one step for an int?
Keep practising
Check Whether a Number Is a Magic Number
Hints · Dry run · SolutionSolve Similar problemFind the Digital Root of a Number
Hints · Dry run · SolutionSolve Similar problemFind the Sum of the Digits of a Number
Hints · Dry run · SolutionSolve Related learningLoops
TutorialLearn Related learningHashset
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
