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
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
解题思路:建立一个vector,里面装得是新生成的数字,如例子中的19,82,68,100,每次产生一个新的数字就到这个vector中查询是否已经存在,如果已经存在,则必定会陷入循环;如果不存在,则加入到vector,继续生成新的数字。
class Solution {
public:
vector<int> vec;
bool isHappy(int n) {
if(n==1) return true;
vector<int>::iterator it=find(vec.begin(),vec.end(),n);
if(it==vec.end()){//在vector中没有找到该数字。
vec.push_back(n);
int total=0;
while(n){
total+=(n%10)*(n%10);
n/=10;
}
return isHappy(total);
}else{
return false;
}
}
};