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

  1. Sum of squares of digits
  2. Keep a counter to detect loops (max 100 iterations)
  3. Stop if result becomes 1

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler