LeetCode (12) - Happy Number(파이썬, python)

1 분 소요

❓ 문제

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:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Example 2:

Input: n = 2
Output: false

Constraints:

  • 1 <= n <= 231 - 1

Given Code

class Solution:
    def isHappy(self, n: int) -> bool:
        

내 풀이

class Solution:
    def isHappy(self, n: int) -> bool:
        def cal(target: int):
            sum = 0
            for s in str(target):
                sum += (int(s))**2
            return sum

        while(n > 9):
            n = cal(n)
            print(n)
        if n == 1 or n == 7:
            return True
        else:
            return False

cal이라는 함수로 자릿수별 제곱 합을 return 하도록 했다.

한자리수 되었을때 1, 7이 아니면 무한루프가 도는데… 뭔가 다들 한번 돌았던 수의 목록을 저장해서 회피하던데 나는 1이나 7이라는 수를 명시해줬다.

(두, 세자리수에서 루프 도는 케이스는 없나…? 그러면 내 코드에서 루프 돌꺼같은데)