Happy Number
2016-07-12 06:49
225 查看
Writeanalgorithmtodetermineifanumberishappy.
Ahappynumberisanumberdefinedbythefollowingprocess:Startingwithanypositiveinteger,replacethenumberbythesumofthesquaresofitsdigits,andrepeattheprocessuntilthenumberequals1(whereitwillstay),oritloopsendlesslyinacyclewhichdoesnotinclude1.Thosenumbersforwhichthisprocessendsin1arehappynumbers.
Example
19isahappynumber
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; } }
相关文章推荐
- iGrimace V8 ios8系统越狱的手机安装方式:
- Android 按钮事件两种经典写法
- BaseAdapter的用法
- 【转】mac os x系统上Android开发环境的搭建
- Android中Bitmap, Drawable, Byte,ID之间的转化
- 保存数据到手机内存
- Scroll实现上下左右滑动
- 写了一个判断水仙花数的小程序,本人新手,勿喷!求指点!
- View 1
- Intent传递类对象值
- 关于百度地图的 230错误 APP Scode校验失败问题
- Android自定义View——自由定制优惠券背景
- Unity3D教程之Roll a Ball
- 内网环境搭建微信公众号的JAVAWEB应用服务器
- 【Xamarin报错】visual studio android 模拟器部署卡住
- android LinearLayout嵌套 button、imagebutton时onClickListener不响应的问题
- Android自定义ViewGroup(一)——带箭头的圆角矩形菜单
- Unity5.3.5的AssetBundle加载
- JavaScript的时钟小程序
- iOS学习笔记