Write an algorithm to determine if a number is "happy".
a Happy number is A number defined by the following process:starting with any positive integer, replace the number by th e sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops end lessly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.
example: is a happy number
The topic is also relatively simple, the AC code is as follows:
BOOLIshappy (intN) {if(n<=0) return false; Else if(n==1) return true; Else { intsqusum=N; intlut[Ten]; for(intI=0;i<Ten; i++) Lut[i]= i*i; Vector<int>sum; while(squsum!=1) {sum.push_back (squsum); inttmp=squsum; Squsum=0; while(tmp>=Ten) {squsum=squsum+lut[tmp%Ten]; TMP=tmp/Ten; } squsum=squsum+Lut[tmp]; if(Squsum = =1) return true; Vector<int>::iterator result =Find (Sum.begin (), Sum.end (), squsum); if(Result! =sum.end ()) Break; } return false; } }
Note that using the lookup table, you can save a little time.
Leetcode "202" Happy number