Skip to content

Commit 7440a75

Browse files
refactor 202
1 parent 47cbcd5 commit 7440a75

File tree

1 file changed

+18
-14
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-14
lines changed

src/main/java/com/fishercoder/solutions/_202.java

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
* Those numbers for which this process ends in 1 are happy numbers.
1616
*
1717
* Example: 19 is a happy number
18-
*
1918
* 12 + 92 = 82
2019
* 82 + 22 = 68
2120
* 62 + 82 = 100
@@ -27,22 +26,27 @@ public boolean isHappy(int n) {
2726
if (n == 1) {
2827
return true;
2928
}
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)) {
4235
return false;
4336
}
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;
4448
}
45-
return false;
49+
return result;
4650
}
4751
}
4852
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy