Skip to content

Commit 9d764fd

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 202 Happy Number
1 parent 791b275 commit 9d764fd

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1717
- [125 Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/)
1818
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1919
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
20+
- [202 Happy Number](https://leetcode.com/problems/happy-number/description/)
2021
- [205 Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/)
2122
- [242 Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
2223
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def sum_of_squares(self, n: int) -> int:
3+
return sum(int(digit) ** 2 for digit in str(abs(n)))
4+
5+
def isHappy(self, n: int) -> bool:
6+
"""
7+
Write an algorithm to determine if a number n is happy.
8+
9+
A happy number is a number defined by the following process:
10+
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
11+
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
12+
- Those numbers for which this process ends in 1 are happy.
13+
14+
Return true if n is a happy number, and false if not.
15+
"""
16+
values = {}
17+
while n != 1:
18+
if n in values:
19+
return False
20+
values[n] = True
21+
n = self.sum_of_squares(n)
22+
return True

tests/test_202_happy_number.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._202_happy_number import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["n", "expected"],
8+
argvalues=[
9+
(19, True),
10+
(2, False),
11+
],
12+
)
13+
def test_func(n: int, expected: bool):
14+
is_happy = Solution().isHappy(n)
15+
assert is_happy == expected

0 commit comments

Comments
 (0)