How to check if a number is a happy number in Java

1 Answer

0 votes
// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

public class MyClass {
    private static int isHappyNumber(int num) {
    	int sum = 0;
    
    	while (num > 0) {
    		int reminder = num % 10;
    		sum = sum + (reminder * reminder);
    		num = num / 10;
    	}
    
    	return sum;
    }

    public static void main(String args[]) {
        int num = 82;
	    int result = num;

	    while (result != 1 && result != 4) {
		    result = isHappyNumber(result);
	    }

	    if (result == 1) {
		    System.out.print("Happy number");
	    }
	    else if (result == 4) {
		    System.out.print("Not a happy number");
	    }
    }
}




/*
run:

Happy number

*/

 



answered Nov 15, 2022 by avibootz
...