I wrote a code which had the same logic except for the fact that I initialised both slow and fast pointers to square of n. When running the code, test case 19 is failing. I dry ran and I am getting the correct result. If I initialise slow pointer to n and fast pointer to n square then all test cases are passing. I feel there is a mistake here. Initialisation of pointers shouldn’t matter.
Here is the code that I tried.
public static boolean isHappyNumber(int n) {
// Replace this placeholder return statement with your code
if (n==1){
return true;
}
int slow = sumOfSquaresOfDigits(n);
int fast = sumOfSquaresOfDigits(n);
while( fast != 1 && slow != fast){
slow = sumOfSquaresOfDigits(slow);
fast = sumOfSquaresOfDigits(sumOfSquaresOfDigits(fast));
}
return fast==1 ;
}
public static int sumOfSquaresOfDigits(int num){
int result = 0;
while(num!=0){
int lastDigit = num%10;
num = num/10;
result += Math.pow(lastDigit, 2);
}
return result;
}
Course: Grokking Coding Interview Patterns in Java - Learn Interactively
Lesson: Happy Number