【LEETCODE】202-Happy Number
来源:互联网 发布:一号店在线客服软件 编辑:程序博客网 时间:2024/06/05 19:13
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
用哈希表记录每个出现过的sum,
当sum不是1并且再次出现的时候,说明进入循环,则返回false
当sum是1的时候,则返回true
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ t=set() #定义一个哈希表 while n!=1 and n not in t: #当n是1时,说明是happy,返回true,当n在t但不是1时,说明循环,返回false t.add(n) #将n加入哈希表里 s=0 while n!=0: a=n%10 s+=a*a #对每一位的数求平方,再加和 n=int(n/10) n=s #n变成最后的和s return n==1 #if s not in t.key(): #t.add(s) #n=s #else: #return False
0 0
- LeetCode 202 Happy Number
- LeetCode 202-Happy Number
- leetcode-202 Happy Number
- leetcode 202: Happy Number
- [LeetCode 202]Happy Number
- leetcode 202 Happy Number
- leetCode #202 Happy number
- LeetCode 202 : Happy Number
- LeetCode 202:Happy Number
- Happy Number - LeetCode 202
- Leetcode[202]-Happy Number
- LeetCode---(202)Happy Number
- Leetcode 202 Happy Number
- leetcode-202 Happy Number
- leetcode 202:Happy number
- leetcode[202]:Happy Number
- leetcode-202-Happy Number
- LeetCode #202 Happy Number
- Fragment 和 FragmentActivity的关系
- mysql分区功能详细介绍,以及实例
- 通过地址url在myeclipse中找到对应的程序
- 关于磁盘分区
- myeclipse启动tomcat速度慢的问题
- 【LEETCODE】202-Happy Number
- (转载)新入职的程序员如何避免痛苦和迷茫?
- 【shader】Unity3D地形
- Qt4转Qt5遇到的问题
- “纯粹”的面向对象程序设计方法是什么样的
- LeetCode 38 Count and Say(计数与报数)
- R にラムダ式を導入するパッケージ lambdaR を作った
- linux oracle 创建表空间,用户,赋权限
- java调用.net webservice