Enter a number to check if it's a Happy Number: 19
19 is a Happy Number!
import java.util.HashSet;
import java.util.Scanner;
public class HappyNumberChecker {
// Function to calculate the sum of squares of digits
public static int sumOfSquares(int number) {
int sum = 0, digit;
while (number > 0) {
digit = number % 10; // Extract the last digit
sum += digit * digit; // Add the square of the digit
number /= 10; // Remove the last digit
}
return sum;
}
// Function to check if a number is a Happy Number
public static boolean isHappyNumber(int number) {
HashSet<Integer> seenNumbers = new HashSet<>();
while (number != 1 && !seenNumbers.contains(number)) {
seenNumbers.add(number); // Track visited numbers
number = sumOfSquares(number); // Update the number
}
return number == 1; // Return true if it reaches 1
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check if it's a Happy Number: ");
int number = scanner.nextInt();
if (isHappyNumber(number)) {
System.out.println(number + " is a Happy Number!");
} else {
System.out.println(number + " is NOT a Happy Number.");
}
scanner.close();
}
}
Enter a number to check if it's a Happy Number: 20
20 is NOT a Happy Number.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.