关键是当一个数不是happy number是,怎样退出循环
自己的挫方法:使用set保存之前计算的所有数
class Solution {
public:
bool isHappy(int n) {
if(n <= 0) return false;
if(n == 1) return true;
set<int> prev;
prev.insert(n);
while(n != 1){
int sum = 0;
while(n){
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
n = sum;
if(prev.count(n)) return false;
prev.insert(n);
}
return true;
}
};
discuss里面的方法1: Using fact all numbers in [2, 6] are not happy (and all not happy numbers end on a cycle that hits this interval)
class Solution {
public:
bool isHappy(int n) {
if(n <= 0) return false;
while(n > 6){
int next = 0;
while(n){
int tmp = n % 10;
next += tmp * tmp;
n /= 10;
}
n = next;
}
return n == 1;
}
};
discuss里面的方法2:Use the same way as checking cycles in a linked list
class Solution {
public:
bool isHappy(int n) {
if(n <= 0) return false;
int A = nextNum(n); //A指向第一个
int B = nextNum(A); //B指向第二个
while(A != 1 && A != B){
A = nextNum(A); //A每次向前走一步
B = nextNum(B); //B每次向前走两步
B = nextNum(B);
}
return A == 1;
}
int nextNum(int n){
int next = 0;
while(n){
int tmp = n % 10;
next += tmp * tmp;
n /= 10;
}
return next;
}
};