[Leetcode/Python] Happy Number

지구인 ㅣ 2022. 11. 29. 12:03

728x90
Top Interview Questions 의 Medium Collection에 있는 문제입니다.         
문제는 여기서 볼 수 있습니다.

 

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 <= 2^31 - 1

 

Code:

class Solution:
    def isHappy(self, n: int) -> bool:
        sumlist = []
        #1 : 각 자릿수의 제곱합 구하기
        while n not in sumlist:
        	#2: 수가 무한순환하는지 체크하기 위해 sumlist라는 리스트에 저장
            sumlist.append(n)
            sumnum = 0
            while n > 0:
                front, last = divmod(n,10)
                sumnum += last*last
                n = front
            n = sumnum
            #3 : 계산 결과가 1이면 True
            if n == 1:
                return True
        #4 : 각 자릿수의 제곱합이 (1이 나오지 않는)무한순환에 빠질 경우 False 
        return False

 

1. 각 자릿수의 제곱합을 더해서 언젠가 1이 나온다면 True, 1이 나오지 않고 순환에 빠진다면 False를 반환하는 문제입니다.

2. 순환에 빠진다는 것은 각 자릿수의 제곱한이 어느순간 중복해서 나오는 경우를 말합니다.

3. 따라서 순환에 빠진건지 아닌지를 확인하기 위해 1인지 아닌지 비교하는 변수를 매 시도마다 sumlist라는 리스트에 추가해주어 순환 여부를 체크합니다.

4. 코드에 대한 설명은 주석을 참고해주세요.

 

728x90