bool ishappy(int n, int *cnt)
{
(*cnt)++;/* cnt to control the depth of callstack, max is 40 */
if((*cnt) >= 40) {
return false;
}
if(n == 1) return true;
int tmp=0;
while(n) {
tmp += (n%10) * (n%10);
n /= 10;
}
return ishappy(tmp, cnt);
}
bool isHappy(int n){
int cnt = 0;
return ishappy(n, &cnt);
}
/* way2 */
bool isHappy(int n) {
int tmp;
int tmp2;
int ret=0;
int arr[50];
int index=0;
int i;
ret = n;
do {
tmp = ret;
ret = 0;
while(tmp) {
ret += ((tmp%10)*(tmp%10));
tmp /= 10;
}
for(i=0; i<index; i++){
if(arr[i] == ret){
return false;
}
}
arr[index++] = ret;
}while(ret > 1);
return true;
}
LeetCode-202. 快乐数-C语言
最新推荐文章于 2023-05-28 22:22:29 发布