美文网首页
LeetCode#202 Happy Number

LeetCode#202 Happy Number

作者: 如烟花非花 | 来源:发表于2016-11-30 10:22 被阅读64次

问题描述

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,或者在这个循环的过程中没出现过1,并且中间数字没有陷入一个循环,则这个数字是快乐数。概念感觉比较拗口,还是看例子吧。

方案分析

  1. 首先确定的一点是这个是一个循环的过程,并且根据概念发现很容易陷入一个死循环。而打破这个死循环的条件正是不满足快乐数或者满足快乐数的临界点——生成的中间值是否重复过。
  2. 其次,要实现一个目标就是求给定数字每一位的平方和。
  3. 最后,判定的条件是结果是不是为1。

python实现

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        middle = set()
        while(n not in middle):
            middle.add(n)
            n = sum(int(i)**2 for i in str(n))
        return n==1

相关文章

网友评论

      本文标题:LeetCode#202 Happy Number

      本文链接:https://www.haomeiwen.com/subject/dsazpttx.html