标签:
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
bool isHappy(int n) ;
void main()
{
int n=7;
cout<<isHappy(n);
}
bool isHappy(int n) {
if (n<=0) return false;
if (n==1) return true;
vector<int> bit_num,recode;
bool flag=false;
int res=0;
while(n)
{
bit_num.clear();
res=0;
while(n/10)
{
int temp=n%10;
bit_num.push_back(temp);
res+=temp*temp;
n=n/10;
}
if (n%10!=0)
{
bit_num.push_back(n%10);
res+=(n%10)*(n%10);
}
recode.push_back(res);
cout<<res<<endl;
if (res==1)
{
flag=true;
break;
}
else
{
vector<int>::iterator iter;
for (iter=recode.begin();iter!=recode.end()-1;iter++)
{
if (res==*iter&&recode.size()>1)
{
flag=false;
return flag;
}
}
n=res;
}
}
return flag;
}标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45195255