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
题源:here
思路:
我们使用一个set来保存所有出现过的数,如果这个数再一次出现,那么说明开始循环了;如果我们发现这个数最终累加到1,那么直接返回true。
class Solution {
public:
bool isHappy(int n) {
set<int> s;
s.insert(n);
while(n!=1){
n = helper(n);
if(s.find(n) == s.end()) s.insert(n);
else return false;
}
return true;
}
int helper(int a){
vector<int> ivec;
while(a){
int tmp = a % 10;
ivec.push_back(tmp*tmp);
a /= 10;
}
return accumulate(ivec.begin(), ivec.end(), 0);
}
};