class Solution {
public:
bool isHappy(int n) {
int m = n;
map<int, int> sums;
int sum = 0;
while(sums[sum] == 0) {
sums[sum] = 1;
sum = 0;
while(m) {
int r = m % 10;
sum = r * r;
m = m / 10;
}
if(sum == 1) {
return true;
}
m = sum;
}
return false;
}
};
Version 2
代码语言:javascript复制
class Solution {
public:
bool isHappy(int n) {
int slow = calDigits(n);
int fast = calDigits(slow);
while(slow != 1 && slow != fast) {
slow = calDigits(slow);
fast = calDigits(fast);
fast = calDigits(fast);
}
return slow == 1;
}
private:
int calDigits(int m) {
int sum = 0;
while(m) {
int r = m % 10;
sum = r * r;
m = m / 10;
}
return sum;
}
};