202. Happy Number
LeetCode 202. Happy Number
Description
Write an algorithm to determine if a number n
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.
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.
Return true
if n
is a happy number, and false
if not.
Example 1:
Example 2:
Constraints:
1 <= n <= 231 - 1
Tags
Two Pointers, Hash Table, Math
Solution
In essential, this problem implies a linked list structure. Thus, we can come up with the idea of using fast and slow pointers to solve it. If faster pointer can reach 1, return true. Otherwise, there is a cycle in this implicit linked list, and we can expect two pointers should meet with each other, then return false.
Complexity
Code
Reference
Last updated
Was this helpful?