File tree 1 file changed +18
-14
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +18
-14
lines changed Original file line number Diff line number Diff line change 15
15
* Those numbers for which this process ends in 1 are happy numbers.
16
16
*
17
17
* Example: 19 is a happy number
18
- *
19
18
* 12 + 92 = 82
20
19
* 82 + 22 = 68
21
20
* 62 + 82 = 100
@@ -27,22 +26,27 @@ public boolean isHappy(int n) {
27
26
if (n == 1 ) {
28
27
return true ;
29
28
}
30
- Set <Integer > set = new HashSet ();
31
- while (n != 1 ) {
32
- String str = String .valueOf (n );
33
- n = 0 ;
34
- for (int i = 0 ; i < str .length (); i ++) {
35
- int temp = Character .getNumericValue (str .charAt (i ));
36
- n += temp * temp ;
37
- }
38
- if (n == 1 ) {
39
- return true ;
40
- }
41
- if (!set .add (n )) {
29
+ Set <Integer > seen = new HashSet ();
30
+ seen .add (n );
31
+ int result = 0 ;
32
+ while (result != 1 ) {
33
+ result = getResult (n );
34
+ if (seen .contains (result )) {
42
35
return false ;
43
36
}
37
+ seen .add (result );
38
+ n = result ;
39
+ }
40
+ return true ;
41
+ }
42
+
43
+ private Integer getResult (int num ) {
44
+ int result = 0 ;
45
+ while (num != 0 ) {
46
+ result += (num % 10 ) * (num % 10 );
47
+ num /= 10 ;
44
48
}
45
- return false ;
49
+ return result ;
46
50
}
47
51
}
48
52
}
You can’t perform that action at this time.
0 commit comments