leetcode202 Happy Number
2015-10-09 09:10
441 查看
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
import java.util.ArrayList; import java.util.HashSet; public class Solution { public boolean isHappy(int n) { if(n<1) return false; if(n==1) return true; int last = 0; int cur = n; HashSet<Integer> map = new HashSet<Integer>(); while(last!=cur && !map.contains(cur)){ ArrayList< Integer> num = length(cur); last = cur; map.add(cur); cur = 0; for(int i = 0;i<num.size();i++){ cur+=(num.get(i)*num.get(i)); } } if(cur == last && last==1) return true; else{ return false; } } public static ArrayList<Integer> length(int x){ ArrayList<Integer> num = new ArrayList<Integer>(); while(x!=0){ int b = x%10; num.add(b); x = x/10; } return num; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(new Solution().isHappy(2)); } }
相关文章推荐
- Android各层推荐开发书籍及参考资料
- android popwindow的使用
- 单个angular页面能否有两个ng-app?
- Android SDK 代理设置
- android 调用系统照相机拍照后剪裁
- iOS分析远程推送的步骤
- iOS 8 新特性介绍
- 【投稿】iOS 9:快速让你的APP支持spotlight搜索
- iOS开发-常用第三方开源框架介绍
- TouchSlop的初步认识(Android 判断触摸时是否滑动事件的常量)
- 深入浅出聊Unity3D项目优化:从Draw Calls到GC
- iOS 数组越界 Crash处理经验
- Android开发常用的一些功能模块
- android 获取设备Configuration配置信息
- AngularJS 之iOS 移动 APP 混合开发(原生+JS)
- iOS9 隐藏状态栏
- Apple Watch开发Glance界面指南
- Android开发总结笔记 ImageView(图像视图) 1-1-8
- Android系统的常用权限
- IOS-8-Xcode6 使用MJRefresh报错:Too many arguments to function call, expected 0, have 3