202. 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:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
解法
用一个hashset来存储每一次拆分的平方和,用到HashSet中add方法,它会先比较hashcode是否相同,如果hashcode不同的话,直接写进去,如果相同的话会比较equals方法。即是作用在如果出现相同的失败的和就没必要再进行拆分相加下去。
java
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<Integer>();
int sum=0;
int remain;
while(set.add(n))
{
sum=0;
while(n!=0)
{
remain = n%10;
sum=sum+remain*remain;
n=n/10;
}
if(sum==1) return true;
n=sum;
}
return false;
}
}
python,用到set(集合),它只允许存在不重复元素,如果add添加的元素已经存在,则不能添加,可以用一个if n in来判断是否存在,不存在则添加,存在则返回false
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
sum = set()
while n!=1:
s=0
while n!=0:
r=n%10
s=s+r*r
n=n/10
n=s
if n not in sum:
sum.add(n)
else:
return False
return True