[LeetCode][数论]Happy Number
来源:互联网 发布:数据质量考核办法 编辑:程序博客网 时间:2024/04/28 04:12
题目描述:
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; }}
0 0
- [LeetCode][数论]Happy Number
- [leetcode] Happy Number
- leetcode: Happy Number
- [LeetCode] Happy Number
- [LeetCode]Happy Number
- LeetCode 202 Happy Number
- LeetCode OJ Happy Number
- [LeetCode]202.Happy Number
- LeetCode 202-Happy Number
- leetcode-202 Happy Number
- [LeetCode]Happy Number
- leetcode 202: Happy Number
- leetcode Happy Number
- [LeetCode 202]Happy Number
- LeetCode (24) Happy Number
- LeetCode Happy Number 题解
- [LeetCode] Happy Number
- leetcode 202 Happy Number
- 【MySQL】性能优化之 覆盖索引
- C++ 容器及选用总结
- socket通信简介
- IOS 封装上线 All object files and libraries for bitcode must be generated from.
- 提高ArcSDE GeoDataBase写入效率
- [LeetCode][数论]Happy Number
- oneToMany
- 大数阶乘的位数
- 数据结构之:链表详解
- 《码农(第12期)》的笔记
- springMVC 上传文件同时传递参数
- (转)JAVA虚拟机的生命周期
- ListView和GridView与ScrollView冲突只显示一行的问题
- iOS中飞行模式或无网提示