# 202. Happy Number 快乐数

@TOC

[LeetCode]

Total Accepted: 36352 Total Submissions: 109782 Difficulty: Easy

## # 题目描述

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:

``````Input: 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
``````

## # 解题方法

### # 递归

``````public static boolean isHappy(int n) {
int ans = 0;
if (n == 1 || n == 7) {
return true;
} else if (n > 1 && n < 10) {
return false;
} else {
String numString = "" + n;
char numChar[] = numString.toCharArray();
for (char aNumChar : numChar) {
ans += (aNumChar - '0') * (aNumChar - '0');
}
}
return isHappy2(ans);
}
``````

7通过计算也回到1。

``````public static boolean isHappy(int n) {
int ans = 0;
if (n == 1) {
return true;
} else if (n > 1 && n < 7) {
return false;
} else {
String numString = "" + n;
char numChar[] = numString.toCharArray();
for (char aNumChar : numChar) {
ans += (aNumChar - '0') * (aNumChar - '0');
}
}
return isHappy5(ans);
}
``````

### # 迭代

``````class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
visited = set()
while n not in visited:
nx = 0
while n != 0:
nx += (n % 10) ** 2
n //= 10
if nx == 1:
return True
n = nx
return False
``````

``````class Solution {
public:
bool isHappy(int n) {
unordered_set<int> visited;
visited.insert(n);
while (n != 1) {
int pre = n;
int next = 0;
while (pre) {
next += (pre % 10) * (pre % 10);
pre /= 10;
}
n = next;
if (visited.count(n))
break;
visited.insert(n);
}
return n == 1;
}
};
``````

## # 日期

2015/10/16 16:06:37 2018 年 11 月 19 日 —— 周一又开始了 2019 年 1 月 14 日 —— 凛冬将至