leetcode--Happy Number

来源:互联网 发布:微信 for ubuntu 编辑:程序博客网 时间:2024/06/16 06:12

Write an algorithm to determine if a number 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, and 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 numbers.

Example: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

解:

除了常规用hashtable记录出现过的number以外,可以将问题看成 cycle detecting 的问题用Floyd算法求解
具体算法检验一个链表是否存在环?以及环的开始位置
想象龟兔从同一起点同时出发,乌龟速度为1,兔子速度为2,如果链表存在环的话乌龟和兔子最终会相遇在环上某一点,如果不存在环,两者最终都会到达终点。
对于求取环的开始位置,假设乌龟和兔子t时间后在某点相遇,将乌龟(或兔子)放到最初起点,兔子(乌龟)仍在相遇点,两者以相同速度1继续前进,再次相遇的位置即为环的起始点。

class Solution(object):    def isHappy(self, n):        """        :type n: int        :rtype: bool        """        if n==1:return True        fast=self.square(self.square(n))        slow=self.square(n)        while slow!=fast:            if slow==1:return True            fast=self.square(self.square(fast))            slow=self.square(slow)        if slow==1:return True        return False    def square(self,n):        digits=[]        while n!=0:            digits.append(n%10)            n/=10        n=sum([d*d for d in digits])        return n
0 0
原创粉丝点击