Q202 Happy Number

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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
解题思路:

根据题意,最后结果为 1 是 happy number,返回 True,否则必定出现环,不是 happy number 返回 False。

在写代码的时候,happy number 的终止条件容易得到(循环过程中平方和等于1即可)。但是,不是 happy number 的终止条件不容易找到。

但是,发现一个规律:如果出现环,则这个环中必定出现 4 这个数字。比如5,循环结果依次是:

25,29,85,89,145,42,20,4,16,37,58,89,145,42,20,4......

其他不是 happy number 的也有这样的规律。因此,循环终止的条件就可以找到了。

Python实现:
class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        while True:
            n = sum([int(ch)**2 for ch in str(n)])
            if n == 1: return True
            if n == 4: return False

a = 19
b = 8
c = Solution()
print(c.isHappy(a))  # True
print(c.isHappy(b))  # False
补充:

如果观察不到这个规律,我可能使用快慢指针解决是否有环的问题。慢指针 slow 每次只计算一次平方和,快指针 fast 每次计算两次平方和。如果快指针追上慢指针(fast = slow),且慢指针不为1,则代表有环,不是 happy number,否则为 happy number。

快慢指针的思路来源于判断链表是否有环的问题:Q141 Linked List Cycle

关于快慢指针:

快慢指针可以解决这样的问题:

  1. 判断链表是否有环(设置两个指针,慢指针每次走一步,快指针每次走两步,如果有环,两指针总会相遇);
  2. 求链表中点(设置两个指针,慢指针每次走一步,快指针每次走两步,当快指针走到链表尾,慢指针刚好到链表中点);
  3. 求链表倒数第n个数(设置两个指针,快指针先走n步,然后慢指针和快指针一起走,当快指针到达链表尾,慢指针刚好为倒数第n个数);
  4. 如果链表有环,求环的入口(设置两个指针,一个指针指向相遇点,一个指针指向链表头。每次各走一步,再次相遇的点就是环入口)。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,140评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,735评论 0 38
  • 10.22 1.52次加速,助你成为“超级个体” 2.热题思考:你是一辆什么车? 职业发展计划:目标-自我-路径...
    Sim2阅读 936评论 0 0
  • strive邱邱阅读 1,267评论 2 2