"Leetcode" Happy Number--easy

Source: Internet
Author: User

Happy number if the sum of the squares of the integers of each bit of one digit equals 1

Example:19 is a happy number

    • 12 + 92 = 82
    • 82 + 22 = 68
    • 62 + 82 = 100
    • 12 + 02 + 02 = 1
#include <iostream>#include<vector>#include<math.h>using namespacestd;classSolution { Public:    BOOLIshappy (intN) {Temp.insert (Temp.begin (), n); //Add the current value to the history path        intR=addsquare (N,0); if(r==1)//if the condition of happy number has been reached            return true; Else        {             for(vector<int>::iterator It=temp.begin (); It!=temp.end (); it++)//if the condition for happy number is not met, then compare r and historical values for coincident            {                if(r==*it)return false;//If it is coincident with the historical value, it is not happy number} ishappy (R); //if there is no overlap with historical results, continue to calculate backwards        }        }Private: Vector<int>temp; intAddsquare (intNintR) {            //Char str[11]; //itoa (n,str,10); //the number is converted to a string, and 10 represents a 10 binary//int r=0; //Char *ptr=str; //While (*ptr!= ')//{            //r+= (*ptr-' 0 ') * (*ptr-' 0 '); //ptr++; //}            //return R;        inttmp=n%Ten; R+=tmp*tmp; N= (n-tmp)/Ten; if(n==0)            returnR; ElseAddsquare (N,R); }};voidMain () {solution S; intN; CIN>>N; cout<<s.ishappy (n);}

"Leetcode" Happy Number--easy

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.