LeetCode 202. Happy Number(快乐数字)
来源:互联网 发布:加权平均图像融合算法 编辑:程序博客网 时间:2024/06/05 15:18
原题网址:https://leetcode.com/problems/happy-number/
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
方法一:使用哈希集合检测是否重复(环路)。
public class Solution { public boolean isHappy(int n) { Set<Integer> set = new HashSet<>(); while (true) { if (n == 1) return true; if (set.contains(n)) return false; set.add(n); int next = 0; while (n>0) { int digit = n % 10; n /= 10; next += digit * digit; } n = next; } }}
方法二:使用快慢指针检测环路。
public class Solution { private int calc(int n) { int next = 0; while (n>0) { int digit = n % 10; n /= 10; next += digit * digit; } return next; } public boolean isHappy(int n) { int slow = n; int fast = n; while (true) { slow = calc(slow); fast = calc(calc(fast)); if (fast == 1) return true; if (slow == fast) return false; } }}
0 0
- LeetCode 202. Happy Number(快乐数字)
- [LeetCode]202. Happy Number 快乐数
- (LeetCode)Happy Number -- 寻找快乐数
- Leetcode 快乐数Happy Number
- leetcode -- happy number 快乐数
- 202.leetcode Happy Number(easy)[数学 快乐数]
- [LeetCode]202.Happy Number
- 【LeetCode】202.happy number
- LeetCode 202. Happy Number
- [leetcode] 202.Happy Number
- 【leetcode】202. Happy Number
- [leetcode] 202. Happy Number
- 202. Happy Number LeetCode
- leetCode 202. Happy Number
- [LeetCode]202. Happy Number
- leetcode 202. Happy Number
- leetcode 202. Happy Number
- LeetCode *** 202. Happy Number
- LeetCode 201. Bitwise AND of Numbers Range(范围内所有数值的比特与)
- redis笔记总结(一)集群分片
- BeanFactoryPostProcessor和BeanPostProcessor的区别
- Spring的BeanFactoryPostProcessor和BeanPostProcessor
- 线程安全问题
- LeetCode 202. Happy Number(快乐数字)
- Spring中Order接口的作用
- SVM详解(包含它的参数C为什么影响着分类器行为)-scikit-learn拟合线性和非线性的SVM
- LeetCode 286. Walls and Gates
- 基于Spring可扩展Schema提供自定义配置支持
- spring源码分析之——spring 事务管理实现方式 (不太清晰,不明白aop会看不懂)
- spring中注册bean(通过代码动态注册)
- ServiceLoader的使用
- 成为C++高手之第一个程序