LeetCode - 202. Happy Number (Python)

조민수·2024년 6월 4일
0

LeetCode

목록 보기
12/64
post-custom-banner

Easy, 문자열

RunTime : 35 ms / Memory : 16.44 MB


문제

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.


풀이

  • intstr의 과정을 거쳐 1까지 도달하는지 확인하는 문제
  • 무한으로 도는 지를 판단하기 위해 set()을 사용했다.
class Solution:
    def isHappy(self, n: int) -> bool:
        if n == 1:
            return True

        visited = set()
        visited.add(n)

        while 1:
            num = str(n)
            n = 0
            for w in num:
                n += (int(w)**2)
            if n in visited:
                return False
            elif n == 1:
                return True
            else:
                visited.add(n)
profile
사람을 좋아하는 Front-End 개발자
post-custom-banner

0개의 댓글