[LeetCode][数论]Happy Number
2016-03-24 16:27
288 查看
题目描述:
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
思路:
前提:幸福数的每个位上数字的平方和最终一定为1,如果不为1继续拆分当前数,求其各个数位的平方和
过程:各个位的平方和必然需要拆分数字,然后求平方和,借助java字符串进行位的分离是最常用的方法,难点在于无限循环下去如何控制,这个时候可以基于一些现成的数据结构,例如HashSet,每创建一个数就加入HashSet,如果HashSet数据量大到无法插入,则返回false,借助数据结构来帮我们判断是否有足够的内存空间来存放数据
代码实现:
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
思路:
前提:幸福数的每个位上数字的平方和最终一定为1,如果不为1继续拆分当前数,求其各个数位的平方和
过程:各个位的平方和必然需要拆分数字,然后求平方和,借助java字符串进行位的分离是最常用的方法,难点在于无限循环下去如何控制,这个时候可以基于一些现成的数据结构,例如HashSet,每创建一个数就加入HashSet,如果HashSet数据量大到无法插入,则返回false,借助数据结构来帮我们判断是否有足够的内存空间来存放数据
代码实现:
public class Solution { public boolean isHappy(int n) { Set<Integer> numberSet = new HashSet<Integer>(); while(n!=1){ if(numberSet.add(n)==false){ return false; } char[] chars = String.valueOf(n).toCharArray(); int total = 0; for(Character ch:chars){ total += Math.pow(Integer.parseInt(ch+""),2); } n = total; } return true; } }
相关文章推荐
- IOS 封装上线 All object files and libraries for bitcode must be generated from.
- Android中退出多个Activity应用
- android activity onWindowFocusChanged函数的使用场景
- 关于16年2月14日以后上传AppStore出现:Missing iOS Distribution signing identity for...的问题
- 自定义ViewGroup,流式布局FlowLayout
- android 高效加载大图
- Android 特色开发,基于位置的服务
- Win8换成Win7系统问题小结(修改主板BIOS方法)
- Android异常和工具使用笔记
- 微信多客服插件获取openid
- Unity 2d 开发实战
- object-c 结构体
- 听萌妹纸说,如何在微信中直接唤醒第三方App
- AndroidStudio使用常见问题(实时更新)
- IOS 开发 证书显示 此证书签发者无效
- Android 学习笔记(1) —— TextView
- Android 学习笔记(2) —— EditView
- android手机推送消息 (百度云推送)
- 很全的demo,包括调用系统相机全屏拍照并保存,访问系统相册,多项保存照片。
- 如何在Android Studio中添加多个项目