【题目描述】
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.
【思路】将出现过的数存在一张hash表中,一旦重复过同个数字且不为1则说明该数不是happy number,反之若循环中得到1则是。
【代码】
class Solution {
public:
bool isHappy(int n) {
int sum=0;
unordered_set<int> shownums;
if(n<1) return false;
if(n==1) return true;
shownums.insert(n);
sum=n;
while(1){
sum=getsum(sum);
if(sum==1) return true;
else if(shownums.find(sum)!=shownums.end()) return false;
shownums.insert(sum);
}
}
int getsum(int m){
int ans=0;
while(m!=0){
ans+=pow(m%10,2);
m=m/10;
}
return ans;
}
};