In the process of interviewing a state-owned enterprise, I was asked to write a happy number algorithm with a mobile phone, which was not written because of the trouble. Later at home, bored to think of writing an example.
The concept of happiness: In a given carry system, the number of all digits (digits) of the sum of squares, the new number obtained once again the sum of squares of all digits, so repeated, the final result must be 1.
Example:2 8→22+82=68→62+82=100→12+02+02=1
Here's the code:
Private BOOLIshappynum (intNum, list<int>lastnum) { if(Lastnum = =NULL) {Lastnum =Newlist<int>(); } BOOLMark =true; Doublesum =0; Do{sum+ = Math.pow (num%Ten,2); if(Num/Ten==0) {Mark=false; } num= num/Ten; } while(Mark); if(Lastnum.contains (Convert.ToInt32 (sum))) {return false; } Lastnum.add (Convert.ToInt32 (sum)); if(Sum! =1) {returnIshappynum (Convert.ToInt32 (sum), lastnum); }Else{return true; } }
On the algorithm of Happiness number