A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process un
This method will return true , if given number is happy number or else it will return false. We are using set here to avoid infinite loop situation.
Input: 19
Output: true
Explanation:
1*1 + 9*9 = 82
8*8 + 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 + 0*0 = 1
public static boolean isHappy(int n) {
Set seen = new HashSet();
while(n != 1) {
int current = n;
int sum = 0;
while(current != 0) {
sum += (current % 10) * (current % 10);
current /= 10;
}
if(seen.contains(sum)) {
return false;
}
seen.add(sum);
n = sum;
}
return true;
}