Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
Can anyone help me with the happy numbers, whenever I tried it is giving an error or impossible output. Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the following code, to get the result of your choice:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter number: ");

    int n = sc.nextInt();

    int l = String.valueOf(n).length();

    int temp = n;

    int midVar = 0, addVar = 0, i = 0;

    while (temp != 4) {

        midVar = 0;

        while (temp != 0) {

            addVar = temp % 10;

            temp = temp / 10;

            midVar += Math.pow(addVar, 2);

        }

        temp = midVar;

        System.out.println(midVar);

        if (temp == 1) {

            break;

        }

    }

    if (temp == 1) {

        System.out.println("Happy number");

    } else {

        System.out.println("Unhappy number");

    }

}

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Tutorial for Beginners | Java Programming:

Related questions

0 votes
1 answer
asked Feb 11, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...