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.

 

풀이

 

 

각 자리수를 계속해서 제곱하여 숫자가 1이나온다면 행복한 수 , 아니라면 행복하지 않은 수다.

 

수는 계속해서 반복되며, 종료조건은 set에 반복되는 수가 동일하게 나타나면 각 자리의 수를 제곱해서 나오는 순환의 마지막에 도달했다고 판단해서 반복문을 종료시킨다.

 

class Solution(object):
    def isHappy(self, n):
        k = 0
        num_set =set()
        result = False
        while k not in num_set:
            str_n = str(n)
            num_set.add(n)
            num = 0
            for i in range(len(str_n)):
                num += int(str_n[i])**2
            if num == 1:
                result = True
                break
            k = num
            n= num
        return result

 

 

 

다른사람의 코드

def isHappy(self, n: int) -> bool:
        seen = set() # to store all the sum of square if digits
        while n != 1:
            sums = sum([int(digit)**2 for digit in str(n)]) # sum of square of digits
            if sums in seen: # if the sums in present in seen then it will be a endless loop
                return False
            n = sums
            seen.add(n)
        
        return True

요 사람도 set을 사용해서 계속해서 반복해서 값이 나오도록 만들었다. 

생각해보니 해시테이블로 풀어야하는데, set도 해시함수로 만들어진 구조이니 해시함수로 풀었다고 생각해도 되는거겠지..? ㅎㅎ 

'알고리즘 > LeetCode' 카테고리의 다른 글

LeetCode 162.Find Peak Element  (0) 2023.09.05
LeetCode 205. Isomorphic Strings  (0) 2023.09.01
49. Group Anagrams  (0) 2023.09.01
LeetCode 290. Word Pattern  (0) 2023.09.01
LeetCode 242. Valid Anagram  (0) 2023.09.01

+ Recent posts