File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ package MustDoEasyList ;
2+
3+ import java .util .HashMap ;
4+
5+ public class HappyNumber202 {
6+
7+ public static boolean isHappy (int n ) {
8+ if (n < 1 )
9+ return false ;
10+
11+ // to put intermediate squares value
12+ HashMap <Integer , Boolean > map = new HashMap <>();
13+ map .put (n , true );
14+
15+ while (n != 1 ) {
16+ n = getSquareDigits (n );
17+
18+ if (!map .containsKey (n )) {
19+ map .put (n , true );
20+ } else {
21+ return false ;
22+ }
23+ }
24+
25+ return n == 1 ? true : false ;
26+ }
27+
28+ private static int getSquareDigits (int n ) {
29+ int ans = 0 ;
30+ while (n != 0 ) {
31+ int rem = n % 10 ;
32+ ans += rem * rem ;
33+ n /= 10 ;
34+ }
35+ return ans ;
36+ }
37+
38+ public static void main (String [] args ) {
39+ System .out .println (isHappy (19 ));
40+ System .out .println (isHappy (2 ));
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments