Thursday, October 20, 2016

Happy Number(YepMe Interview Question) in Java

Happy Number

I have been interviewed  in YepMe few days back .It was very nice interview taken by the technical interviewer ,simply a nice guy.He asked me this question.So i am giving you its solution what it is and how it works,a complete solution.

Happy Number -- A number is called happy if it leads to 1 after a sequence of steps where in each step number is replaced by sum of squares of its digit ie. if we start with Happy Number and keep replacing it with digits square sum, we reach 1.

Examples:

Input: n = 19
Output: True

19 is Happy Number,See how?

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

As we reached to 1, 19 is a Happy Number.

Input: n = 20
Output: False

A number will not be a Happy Number when it makes a loop in its sequence that is it touches a number in sequence which already been touched. So to check whether a number is happy or not, we can keep a set, if same number occurs again we flag result as not happy.

Sample Code implementation in Java:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HappyNumberSolution
{
public static boolean isHappyNumber(int  n)
{
int slow=n,fast=n;

do
{
              slow = numSquareSum(slow);
     fast = numSquareSum(numSquareSum(fast));
}
while (slow!=fast);
 
return (slow==1);
}


       public static int numSquareSum(int n)
{
   int squareSum=0;
 
   while (n>0)
   {
    squareSum += (n % 10) * (n % 10);
       n /= 10;
}

return squareSum;
}

public static void main(String[] args)
{
int n = 13;  //20

   if (isHappyNumber(n))
     System.out.println(n+" is a Happy Number");
   else
    System.out.println(n+" is not a Happy Number");
}


}

Output:

1) 13 is a Happy Number(for input as 13).
2)20 is not a Happy Number(for input as 20)





No comments: