- Time taken to complete: I forgot, very quick I suppose
- Revisions:
- Tags:
- Algorithms: #Floyd_s_cycle_finding_algorithm
- Difficulty: #difficulty_easy
- Platforms: #leetcode
- Links:
- [link to the problem](https://leetcode.com/problems/happy-number/description/)
- Problem:
- 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_.
- Examples:
- ```
Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input: n = 2
Output: false
```
- Constraints:
-`1 <= n <= 231 - 1`
- Thoughts:
- Intuition:
- It loops endlessly in a cycle, which means we need to use a cycle detection algorithm, which happens to be the [[Floyd's Cycle Finding Algorithm]].
- Approach:
- Use the Floyd's cycle finding algorithm, with two variables
- when fast == slow, cycle is found
- detect if fast is 1, and return values
- Solution:
- Code
- ```java
class Solution {
private int progress(int n) {
int sum = 0;
while (n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
// loop detection
int slow = progress(n);
int fast = progress(slow);
while (slow != fast) {
slow = progress(slow);
fast = progress(progress(fast));
}
return (fast == 1);
}
}
```
-
- Daily reflection [[Daily reflections]]
collapsed:: true
- What I've done
- 写学交论文
- 音乐 improvising
- I met someone, she's gorgeous
- What I've thought #thoughts
- Improvisation is fun :)
- I think I fall in love with someone, I have a strong feeling when she is nearby, and dopamine burst out whenever I talk to her. I don't know if she feel the same (I think to some extent she does. I don't really know, I just follow the flow and enjoy every moment of that). ~~aaand also I erected a lot~~
- Mood
- Generally excited, but sometimes exhausted from these happy feelings, I deserve a good sleep.