如果不是快乐数,那么这一串数字会进入到一个没有1的环里。
int sum_number(int n) {
int sum = 0;
while (n != 0) {
sum += pow(n % 10, 2);
n /= 10;
}
return sum;
}
int compare(int n, int* a,int size) {
for (int i = 0; i < size; i++) {
if (n == a[i]) return 1;
}
return 0;
}
bool isHappy(int n) {
int i = 0;
int size = 1;
int* a = (int*)malloc(sizeof(int)*size);
while (n != 1) {
if (i >= size) {
size = size * 2;
a = (int*)realloc(a, size * sizeof(int));
}
a[i++] = n;
n = sum_number(n);
if (compare(n, a, i) == 1) return false;
}
return true;
}
int sum_number(int n) {
int sum = 0;
while (n != 0) {
sum += pow(n % 10, 2);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int fast=n;
int slow=n;
do{
slow = sum_number(slow);
fast = sum_number(sum_number(fast));
if (fast == 1) return true;
}while (slow!=fast);
return false;
}
int sum_number(int n) {
int sum = 0;
while (n != 0) {
sum += pow(n % 10, 2);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int slow = sum_number(n);
int fast = sum_number(sum_number(n));
if(slow==fast) return true;
while(slow!=fast){
slow = sum_number(slow);
fast = sum_number(sum_number(fast));
if (fast == 1) return true;
}
return false;
}