Skip to content

Commit 29afba8

Browse files
committed
problem: 0202. Happy Number
1 parent 57b41ad commit 29afba8

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

solutions/solution_0202/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# 0202. [Happy Number](https://leetcode.com/problems/happy-number/description/?envType=study-plan-v2&envId=top-interview-150)
2+
3+
Write an algorithm to determine if a number `n` is happy.
4+
5+
A **happy number** is a number defined by the following process:
6+
7+
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
8+
- Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
9+
- Those numbers for which this process **ends in** 1 are happy.
10+
11+
Return `true` _if_ `n` _is a happy number, and_ `false` _if not._
12+
13+
### **Example 1:**
14+
15+
<pre><code><strong>Input:</strong> n = 19
16+
<strong>Output:</strong> true
17+
<strong>Explanation:</strong>
18+
1<sup>2</sup> + 9<sup>2</sup> = 82
19+
8<sup>2</sup> + 2<sup>2</sup> = 68
20+
6<sup>2</sup> + 8<sup>2</sup> = 100
21+
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
22+
</code></pre>
23+
24+
### **Example 2:**
25+
26+
<pre><code><strong>Input:</strong> n = 2
27+
<strong>Output:</strong> false
28+
</code></pre>
29+
30+
### **Constraints:**
31+
32+
- <code>1 <= n <= 2<sup>31</sup> - 1</code>

solutions/solution_0202/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
class Solution:
2+
def isHappy(self, n: int) -> bool: ...
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import TypedDict
2+
3+
from . import Solution
4+
5+
6+
class CaseInput(TypedDict):
7+
n: int
8+
9+
10+
class CaseDict(TypedDict):
11+
input: CaseInput
12+
expected: bool
13+
14+
15+
test_cases: list[CaseDict] = [
16+
{
17+
'input': {'n': 19},
18+
'expected': True,
19+
},
20+
{
21+
'input': {'n': 2},
22+
'expected': False,
23+
},
24+
]
25+
26+
27+
def test_solution():
28+
for test_case in test_cases:
29+
assert Solution().isHappy(**test_case['input']) == test_case['expected']

0 commit comments

Comments
 (0)