Happy Number Check in Java: Explanation & Practice
Check if a number is a happy number
Problem summary
A happy number eventually reaches 1 when you replace it with the sum of squares of its digits. Check if a number is happy.
Starter code
public class Main {
public static void main(String[] args) {
int number = 19; // Test case 1
// Check if happy number
// Print: Is happy: <true/false>
}
}Expected output and test cases
- 19 is happy (1→82→68→100→1)
Is happy: true
- 4 is not happy (loops)
Is happy: false
- 7 is happy
Is happy: true
Hints
- Sum of squares of digits
- Keep a counter to detect loops (max 100 iterations)
- Stop if result becomes 1
Related Core Java Basics exercises
- Practice Number to Words in Java
- Practice Triangle Type Checker in Java
- Practice Strong Number Check in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler