2019-01-21

LeetCode 202. Happy Number.jpg

LeetCode 202. Happy Number

Description

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:

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

描述

一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例:

输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

思路

  • 两个辅助函数:divide函数将所有的一个数拆成单独的数字;square求所有数字的平方和.
  • 我们用一个hash set 来记录已经出现过的结果,如果有一个结果已经出现过且不等于1返回Fasle,如果出现了1返回True.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-20 21:06:07
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-21 18:50:47


class Solution:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        numset = set()
        newn = self.square(self.divide(n))
        # 如果求和的结果没有出现过
        while newn not in numset:
            numset.add(newn)
            newn = self.square(self.divide(newn))
            # 如果等于1,返回True
            if newn == 1: return True
        # 若求和的结果已经出现且不等于1,返回False
        return False

    # 拆分函数,返回list
    def divide(self, n):
        res = []
        while n:
            res.append(n % 10)
            n //= 10
        return res

    # 返回所有数子的平方和
    def square(self, nums):
        return sum([x**2 for x in nums])

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,150评论 0 10
  • 无欲则刚66阅读 942评论 0 0
  • 张爱玲说过:“出名要趁早”。很多人抓住了,还稳稳的抓住了。 这是最好的时代也是最坏的时代,我有一个朋友在普通公司上...
    六月三一阅读 1,878评论 0 0
  • 感恩父母的生养之恩,感恩老师教导智慧之恩,感恩兄弟姐妹 爱人和孩子的关心和帮助,感恩同学同修鼓励和支持,感恩天地万...
    一真一切真阅读 1,215评论 0 2
  • 要给你说的话太多了,从哪里开始呐 先给你看我当时po在朋友圈,但后来害羞就没有给你看的文章 我这个人吧,没有投入感...
    小多不多阅读 1,774评论 0 0