Happy Numbers | Java program to check if a number is happy number ; Returns sum of squares of digits of a number n . For example for n = 12 it returns 1 + 4 = 5 ; Returns true if n is Happy number else returns false . ; A set to store numbers during repeated square sum process ; Keep replacing n with sum of squares of digits until we either reach 1 or we endup in a cycle ; Number is Happy if we reach 1 ; Replace n with sum of squares of digits ; If n is already visited , a cycle is formed , means not Happy ; Mark n as visited ; Driver code
import java . util . * ; class GFG { static int sumDigitSquare ( int n ) { int sq = 0 ; while ( n > 0 ) { int digit = n % 10 ; sq += digit * digit ; n = n / 10 ; } return sq ; } static boolean isHappy ( int n ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; s . add ( n ) ; while ( true ) { if ( n == 1 ) return true ; n = sumDigitSquare ( n ) ; if ( ( s . contains ( n ) && n != ( int ) s . toArray ( ) [ s . size ( ) - 1 ] ) ) return false ; s . add ( n ) ; } } public static void main ( String [ ] args ) { int n = 23 ; if ( isHappy ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }