Write an algorithm to determine if a number n
is happy.
A happy number is a number defined by the following process:
Return true
if n
is a happy number, and false
if not.
Floyd's cycle detection algorithm ์ ์ฌ์ฉํ์. (์ผ๋ช ํ ๋ผ์ ๊ฑฐ๋ถ์ด ์๊ณ ๋ฆฌ์ฆ)
ํ ๋ผ์ digit sum ๊ฐ์ด 1์ด๋ผ๋ฉด Happy Number๊ฐ ํ์คํ๋ฏ๋ก ๋ฉ์ถ๋ค.
๊ฑฐ๋ถ์ด์ ํ ๋ผ๊ฐ ๊ฐ์์ง๋ ์๊ฐ์ด ์ค๊ณ ํ ๋ผ๊ฐ 1์ด ์๋๋ผ๋ฉด ์ฌ์ดํด์ด ํ์ง๋ ๊ฒ -> Happy Number๊ฐ ์๋๋ค.
Floyd's cycle detection algorithm์
ํ ๋ผ์ ๊ฑฐ๋ถ์ด๊ฐ ์ํ์ ํธ๋์์ ๋ฉ์ถ์ง ์๊ณ ๊ฒฝ์ฃผํ ๋ (cycle)
ํ ๋ผ๊ฐ ๋ ๋น ๋ฅด๋ฏ๋ก ๊ฑฐ๋ถ์ด์ ๋ฐ๋์ ๊ฐ์ ์์น์์ ๋ง๋๊ฒ ๋๋ค๋ ์๋ฆฌ.
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