반응형
Happy Number
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
- Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input: n = 2
Output: false
Constraints:
1 <= n <= 231 - 1
class Solution:
def isHappy(self, n: int) -> bool:
visited = set()
while n != 1 :
if n in visited :
return False
visited.add(n)
n = sum(int(num)**2 for num in str(n))
return True
10으로 나눈 나머지와 10씩 나누는 방법을 생각하다가 문자로 바꾼 후에 for문으로 하나씩 뽑아서 계산하는거랑 크게 다르지 않아서 이렇게 코드를 작성했다.
순환하지 않으면 1로 수렴하기 때문에 순환하는 구조를 찾아야 한다. 그렇기 때문에 visited 집합을 하나 만들고, n 이 1이 될 때까지 돌리면 된다. 만약 visited에 있는 숫자가 발견되면 그때는 순환하는 구조이기 때문에 1이 되지 않는다.
이 특성을 아냐 모르냐에서 이 문제를 해결할 수 있냐 없냐로 나뉘는 것 같다. 그리고 나는 이걸 알았는데, 못풀었다.
순환하는 구조이다 => 방문 체크를 하자 로의 생각의 흐름을 이해하지 못한 듯 하다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 222. Count Complete Tree Nodes (0) | 2026.03.07 |
|---|---|
| [Leetcode/파이썬] 133. Clone Graph (0) | 2026.03.07 |
| [Leetcode/파이썬] 226. Invert Binary Tree (0) | 2026.03.07 |
| [Leetcode/파이썬] 103. Binary Tree Zigzag Level Order Traversal (0) | 2026.03.01 |
| [Leetcode/파이썬] 102. Binary Tree Level Order Traversal (0) | 2026.03.01 |