• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
November 01, 2022 |810 Views
Java program to check Happy Number
  Share  2 Likes
Description
Discussion

In this video, we will write a Java program to check whether a number is happy or not. 


What is a happy number? 


A number if we sum the square of it’s digit and repeat this process until we get 1 then that number is known as happy. 

But there are cases when this process goes into an infinite loop so, those numbers are termed as unhappy numbers. To detect happy numbers there are 2 methods which we will be looking at in this video one is a brute force method which is implemented by using a HashSet. The time and space complexity of this algorithm is O(N) and O(logN). This is not an optimized approach and needs extra space. 

There is a famous algorithm in linked list that is known as Floyd Cycle Detection Algorithm and is implemented by using two pointers this helps us to remove that extra space complexity of O(N) and does the same task in O(1) that is constant space. This algorithm is quite famous to detect loops in Linked List but we can use it here as well for our purpose. 

Read More