Happy number
2015-08-06 21:13
375 查看
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
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 =
1
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
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 =
1
public class Solution { public boolean isHappy(int n) { HashSet<Integer> set = new HashSet<Integer>(); while(n!= 1){ if(set.contains(n)){ return false; } set.add(n); n = getNextHappy(n); } return true; } public int getNextHappy(int n){ int sum = 0; while(n != 0){ sum += (n%10)*(n%10); n /= 10; } return sum; } }
相关文章推荐
- Android 基于蓝牙的方向控制器
- WebView之2
- Android如何跳过小米和魅族手机对Toast的限制
- ios越狱开发随感
- APP应用完美退出的方法的尝试
- Android Service组件
- Android中visibility属性VISIBLE、INVISIBLE、GONE的区别
- android 当屏幕截图,你如何改变屏幕内容,他们俩bitmap将合并的图像被一起显示
- IOS性能优化
- iOS Core Animation详解(四)AutoLayout中的动画
- Android使得手机拍照功能的发展(源共享)
- Cocos2d-x 2.0 自适应多种分辨率
- 由浅入深学习自定义控件(4)-滑动开关slidemenu
- Android复习笔记(14)-自定义控件(1)-滑动开关
- ios7 textViewDidChange代理/通知中修改TextView内容崩溃的原因
- The constructor SimpleAdapter(new View.OnClickListener(){}, List<Map<String,Object>>, ..的解决方法
- ios 设计 切图
- Android DVM
- quick cocos map使用
- Android ListView&异步加载的学习(三)——AsyncTask加载图片&运用Lru算法优化图片加载