思路
无限循环—->平方和出现相同的—->可以利用哈希表
算出 存入 为一返回true 重复返回false
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| struct hashTable{ int key; UT_hash_handle hh; };
struct hashTable* set=NULL;
int getsum(int n){ int s=0; while(n){ s+=(n%10)*(n%10); n/=10; } return s; }
void clearHashTable(){ struct hashTable *current, *tmp; HASH_ITER(hh, set, current, tmp) { HASH_DEL(set, current); free(current); } }
bool isHappy(int n) { clearHashTable(); while(1){ if(n==1){ return true; } else{ struct hashTable*tmp; HASH_FIND_INT(set,&n,tmp); if(tmp==NULL){ tmp=malloc(sizeof(struct hashTable)); tmp->key=n; HASH_ADD_INT(set,key,tmp); n=getsum(n); } else{ return false; } } } }
|
这题因为数不是很大,嫌麻烦可以直接用数组,2**31-1,直接把数全变成9,1000也够了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| int getsum(int n){ int s=0; while(n){ s+=(n%10)*(n%10); n/=10; } return s; }
bool isHappy(int n) { n=getsum(n); int nums[1000]={0}; while(n!=1){ if(nums[n]==1){ return false; } else{ nums[n]++; } n=getsum(n); } return true; }
|