# 202. Happy Number

## LeetCode [202. Happy Number](https://github.com/txfs19260817/LeetCode-Go/blob/master/solutions/title/README.md)

### 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:**

```
Input: n = 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
```

**Example 2:**

```
Input: n = 2
Output: false
```

**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

* Time complexity: $$O(\log(n))$$
* Space complexity: $$O(1)$$

### Code

```go
func isHappy(n int) bool {
	step := func(n int) int {
		var sum int
		for m := n; m > 0; m /= 10 {
			sum += (m % 10) * (m % 10)
		}
		return sum
	}
	s, f := n, step(n)
	for f != 1 && s != f {
		s = step(s)
		f = step(step(f))
	}
	return f == 1
}
```

## Reference

1. [快乐数](https://leetcode-cn.com/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/)
