题目
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
题意
判断一个数n是否是“happy”,happy的定义为对n 的各位先平方再求和,循环此操作,如果最后能为求和为1,则”happy”
题解
重点在于最终不为1,会一直循环下去,用unordered_map(或者map ,unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序 )构建求和数与出现的次数之间的关系,一旦其中一个求和数出现两次,则意味着之后不会等于1且循环下去。
C++代码
class Solution {
public:
bool isHappy(int n) {
/*
unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序
*/
unordered_map<int, int>m;
while(true)
{
if(n==1) return true;
int sum=0;
while(n){
sum+=(n%10)*(n%10);
n/=10;
}
m[sum]++;
if(m[sum]==2) return false;
n = sum;
}
}
};
python代码
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while True:
if n==1:
return True
t = 0
while n:
t = t + (n%10) * (n%10)
n = n / 10
n = t
if t in s:
return False
s.add(t)