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