Leetcode :: Happy Number

์ˆ‘์ˆ‘ยท2021๋…„ 5์›” 31์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
103/122
post-thumbnail

Problems

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.


Guess

  • Floyd's cycle detection algorithm ์„ ์‚ฌ์šฉํ•˜์ž. (์ผ๋ช… ํ† ๋ผ์™€ ๊ฑฐ๋ถ์ด ์•Œ๊ณ ๋ฆฌ์ฆ˜)

  • ํ† ๋ผ์˜ digit sum ๊ฐ’์ด 1์ด๋ผ๋ฉด Happy Number๊ฐ€ ํ™•์‹คํ•˜๋ฏ€๋กœ ๋ฉˆ์ถ˜๋‹ค.

  • ๊ฑฐ๋ถ์ด์™€ ํ† ๋ผ๊ฐ€ ๊ฐ™์•„์ง€๋Š” ์ˆœ๊ฐ„์ด ์˜ค๊ณ  ํ† ๋ผ๊ฐ€ 1์ด ์•„๋‹ˆ๋ผ๋ฉด ์‚ฌ์ดํด์ด ํƒ์ง€๋œ ๊ฒƒ -> Happy Number๊ฐ€ ์•„๋‹ˆ๋‹ค.

Floyd's cycle detection algorithm์€
ํ† ๋ผ์™€ ๊ฑฐ๋ถ์ด๊ฐ€ ์›ํ˜•์˜ ํŠธ๋ž™์—์„œ ๋ฉˆ์ถ”์ง€ ์•Š๊ณ  ๊ฒฝ์ฃผํ•  ๋•Œ (cycle)
ํ† ๋ผ๊ฐ€ ๋” ๋น ๋ฅด๋ฏ€๋กœ ๊ฑฐ๋ถ์ด์™€ ๋ฐ˜๋“œ์‹œ ๊ฐ™์€ ์œ„์น˜์—์„œ ๋งŒ๋‚˜๊ฒŒ ๋œ๋‹ค๋Š” ์›๋ฆฌ.

Solution

def next_num(n):
    ret = 0
    while n != 0:
        q,r = divmod(n,10)
        ret += r*r
        n = q

    return ret


class Solution:
    def isHappy(self, n: int):
        slow = n
        fast = next_num(n)

        while slow != fast and fast != 1:
            slow = next_num(slow)
            fast = next_num(next_num(fast))

        return fast == 1
profile
ํˆด ๋งŒ๋“ค๊ธฐ ์ข‹์•„ํ•˜๋Š” ์‚ฝ์งˆ ์ „๋ฌธ(...) ์ฃผ๋‹ˆ์–ด ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€