w3resource

Java: Check whether a given number is a happy number or unhappy number

Java Numbers: Exercise-10 with Solution

Write a Java program to check whether a given number is a happy number or unhappy number.

Happy number: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle which does not include 1.
An unhappy number is a number that is not happy.
The first few unhappy numbers are 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17, 18, 20.

Pictorial Presentation:

Java: Check whether a given number is a happy number or unhappy number.
Java: Check whether a given number is a happy number or unhappy number.

Sample Solution:

Java Code:

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Example10 {

    public static boolean isHappy_number(int num)
    {
        Set<Integer> unique_num = new HashSet<Integer>();

        while (unique_num.add(num))
        {
            int value = 0;
            while (num > 0)
            {
                value += Math.pow(num % 10, 2);
                num /= 10;
            }
            num = value;
        }

        return num == 1;
    }

    public static void main(String[] args)
    {
        System.out.print("Input a number: ");
        int num = new Scanner(System.in).nextInt();
        System.out.println(isHappy_number(num) ? "Happy Number" : "Unhappy Number");
    }
}

Sample Output:

Input a number: 5                                                                                             
Unhappy Number

Flowchart:

Flowchart: Check whether a given number is a happy number or unhappy number

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find and print the first 10 happy numbers.
Next: Write a Java program to check whether a given number is a Disarium number or unhappy number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

IsPowerOfTwo

Checks if a value is positive power of two.

To understand how it works let's assume we made a call IsPowerOfTwo(4).

As value is greater than 0, so right side of the && operator will be evaluated.

The result of (~value + 1) is equal to value itself. ~100 + 001 => 011 + 001 => 100. This is equal to value.

The result of (value & value) is value. 100 & 100 => 100.

This will value the expression to true as value is equal to value.

public static boolean isPowerOfTwo(final int value) {
    return value > 0 && ((value & (~value + 1)) == value);
}

Ref: https://bit.ly/3sA5d4I

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook