標籤:
如果一個數的每個位的整數的平方和等於1,則為happy number
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 namespace std;class Solution {public: bool isHappy(int n) { temp.insert(temp.begin(),n); //把當前值加入到曆史路徑中 int r=addsquare(n,0); if(r==1) //如果已經達到了happy number的條件 return true; else { for(vector<int>::iterator it=temp.begin();it!=temp.end();it++) //如果沒有達到happy number的條件,那麼比較r值和曆史值是否重合 { if(r==*it) return false; //如果和曆史值重合了,則不是happy number } isHappy(r); //如果和曆史結果沒有重合,則繼續往後計算 } }private: vector<int> temp; int addsquare(int n,int r){ //char str[11]; //itoa(n,str,10); //數字轉換為字串,10代表10進位 //int r=0; //char *ptr=str; //while(*ptr!=‘\0‘) //{ // r+=(*ptr-‘0‘)*(*ptr-‘0‘); // ptr++; //} //return r; int tmp=n%10; r+=tmp*tmp; n=(n-tmp)/10; if(n==0) return r; else addsquare(n,r); }};void main(){ Solution S; int n; cin>>n; cout<<S.isHappy(n);}
【leetcode】happy number--easy