您的位置:首页 > 移动开发

Happy Number

2016-07-12 06:49 225 查看
Writeanalgorithmtodetermineifanumberishappy.

Ahappynumberisanumberdefinedbythefollowingprocess:Startingwithanypositiveinteger,replacethenumberbythesumofthesquaresofitsdigits,andrepeattheprocessuntilthenumberequals1(whereitwillstay),oritloopsendlesslyinacyclewhichdoesnotinclude1.Thosenumbersforwhichthisprocessendsin1arehappynumbers.

Example

19isahappynumber

1^2+9^2=82
8^2+2^2=68
6^2+8^2=100
1^2+0^2+0^2=1

分析:
这题的关键是如何退出循环如果那个数不是hapynumber.这里用了一个方法,就是用hashset保存得到过的数,如果出现重复,那就不是Happynumber.


publicclassSolution{
/**
*@paramnaninteger
*@returntrueifthisisahappynumberorfalse
*/
publicbooleanisHappy(intn){
if(n<1)returnfalse;

Set<Integer>hashSet=newHashSet<Integer>();
hashSet.add(n);

while(n!=1){
n=getNewNumber(n);
if(hashSet.contains(n)){
returnfalse;
}
hashSet.add(n);
}
returntrue;
}

publicintgetNewNumber(intn){
inttotal=0;
while(n!=0){
total+=(n%10)*(n%10);
n=n/10;
}
returntotal;
}
}


publicclassSolution{
intdigitSquareSum(intn){
intsum=0,tmp;
while(n>0){
tmp=n%10;
sum+=tmp*tmp;
n/=10;
}
returnsum;
}

booleanisHappy(intn){
intslow,fast;
slow=fast=n;
do{
slow=digitSquareSum(slow);
fast=digitSquareSum(fast);
fast=digitSquareSum(fast);
}while(slow!=fast);
if(slow==1)returntrue;
returnfalse;
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: