Thursday, October 8, 2020

Happy Number

Problem: In number theory, a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit or it loops endlessly in a cycle which does not include 1.

Example:

Input: 13
Output: true
Explanation: 
12 + 32 = 10
12 + 02 = 1


Approach: If you see the definition of Happy number, you will observed that there will be a cycle always  that means we can use hash to check if the new sum of squares of digits is already in hash and sum is not equal to 1 then given number is not a Happy number and if sum is 1 then number is happy number.

We can do it without using extra storage. We can use approach of finding loop in linked list to solve this question. We can say a number is node then its next will be sum of squares of its digits so we can use similar slow and fast pointer approach here.


Implementation in C#:

        public bool IsHappyNumber(int n)

        {

            int slow = n, fast = n;

            do

            {

                slow = this.SumSquareDigits(slow);

                fast = this.SumSquareDigits(SumSquareDigits(fast));

            } while (slow != fast);

            return slow == 1;

        }


        private int SumSquareDigits(int n)

        {

            int sum = 0;

            while(n != 0)

            {

                sum += (int) Math.Pow(n % 10, 2);

                n /= 10;

            }

            return sum;

        } 

No comments:

Post a Comment