Skip to content

Commit e94e4f9

Browse files
solves happy numbr
1 parent 4d8c9f9 commit e94e4f9

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
| 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ReverseBits.java) |
6161
| 191 | [Number of One Bits](https://leetcode.com/problems/number-of-1-bits) | Easy | [![Python](https://img.icons8.com/color/35/000000/python.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/python/number_of_1_bits.py) |
6262
| 198 | [House Robber](https://leetcode.com/problems/house-robber) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/HouseRobber.java) |
63-
| 202 | [Happy Number](https://leetcode.com/problems/happy-number) | Easy |
63+
| 202 | [Happy Number](https://leetcode.com/problems/happy-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]() |
6464
| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements) | Easy |
6565
| 204 | [Count Primes](https://leetcode.com/problems/count-primes) | Easy |
6666
| 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings) | Easy |

src/HappyNumber.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
public class HappyNumber {
5+
public static boolean isHappy(int number) {
6+
return isHappy(number, new HashSet<>());
7+
}
8+
9+
private static boolean isHappy(long number, Set<Long> sum) {
10+
long sumSquaresDigits = sumDigitSquares(number);
11+
if (sumSquaresDigits == 1) {
12+
return true;
13+
}
14+
if (sum.contains(sumSquaresDigits)) {
15+
return false;
16+
}
17+
sum.add(sumSquaresDigits);
18+
return isHappy(sumSquaresDigits, sum);
19+
}
20+
21+
private static long sumDigitSquares(long number) {
22+
long result = 0;
23+
while (number > 0) {
24+
result += Math.pow(number % 10, 2);
25+
number /= 10;
26+
}
27+
return result;
28+
}
29+
}

0 commit comments

Comments
 (0)