On the algorithm of Happiness number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.