或许你不知道的是,Leetcode 中是有不少 数学题 的,本文要解析的题 快乐数 就是其中到一个典型问题,本题将基于数据结构 set 来求解。git
今天要给你们分析的面试题是 LeetCode 上第 202 号问题,面试
LeetCode - 202. 快乐数算法
https://leetcode-cn.com/problems/happy-number/数据结构
编写一个算法来判断一个数是否是“快乐数”。app
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每一个位置上的数字的平方和,而后重复这个过程直到这个数变为 1,也多是无限循环但始终变不到 1。若是能够变为 1,那么这个数就是快乐数。ide
示例:函数
输入: 19输出: true
解释:测试
贡献者: LeetCodespa
题目难度: Easy3d
相关话题
相关话题
哈希表
https://leetcode-cn.com/tag/hash-table/
数学
https://leetcode-cn.com/tag/math
类似题目
各位相加
https://leetcode-cn.com/problems/add-digits/ 难度: 简单
丑数
https://leetcode-cn.com/problems/ugly-number/ 难度: 简单
解题思路:
中学数学中咱们学到一个概念集合(英文是set),集合的最大特色是元素不能重复。Python中,set是一组key的集合。
因而可使用迭代法和set这种数据结构来求解此题。
具体操做为: 迭代地求给定数的各位数字的平方和,维护一个set,迭代循环的出口是平方和为1或已在set中出现过。
已 AC
的代码为:
class Solution:
def isHappy(self, n: int) -> bool:
unhappy = set()
while n not in unhappy and n != 1:
unhappy.add(n)
n = self.GetSquareSum(n)
return n == 1
def GetSquareSum(self, n: int) -> bool:
sum0 = 0
while n > 0:
r = n - int(n/10)*10
n = int(n/10)
sum0 += r * r
return sum0
运行结果:
执行用时 : 36ms
, 在全部 Python3 提交中击败了 99.72%
的用户
代码要点:
Python 中 "/" 并非 C 语言中的 "/"(整除),Python 中 / 的结果是浮点数,若是须要获得整数,需使用 "//",也可以使用 int() 函数来处理
Python的 同一个 class 中一个函数 a 调用另外一个函数 b,只需使用关键字 def 定义好函数 a 和 函数 b,在 a 中使用 self.b 便可
相应的,如需测试,本地可执行的代码为:
class Solution:
def isHappy(self, n: int) -> bool:
unhappy = set()
while n not in unhappy and n != 1:
unhappy.add(n)
n = self.GetSquareSum(n)
return n == 1
def GetSquareSum(self, n: int) -> bool:
sum0 = 0
while n > 0:
r = n - int(n/10)*10
n = int(n/10)
sum0 += r * r
return sum0
sol = Solution()
print(sol.isHappy(19))
系列文章