Title
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就是happy number,只要在这个循环中有1就可以了。
Solution
//cpp:
class Solution {
public:
bool isHappy(int n) {
int t1, t2;
unordered_set<int> uset;
while (uset.find(n)==uset.end()) {
uset.insert(n);
t1 = 0;
while (n > 0) {
t2 = n % 10;
t1 += t2*t2;
n /= 10;
}
if (t1 == 1)
return true;
else
n = t1;
}
return false;
}
};