Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add solution of 202.Happy Number(java) #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
yanglbme merged 1 commit into doocs:master from Wushiyii:mysolu-leetcode
Jan 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions solution/0202.Happy Number/README.md
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
## 快乐数
### 题目描述

编写一个算法来判断一个数是不是"快乐数"。

一个"快乐数"定义为:

对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例:
```
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
```

### 解法
在进行验算的过程中,发现一个规律,只要过程中得到任意一个结果和为4,那么就一定会按 `4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4`
进行循环,这样的数就不为快乐数;此外,结果和与若是与输入n或者上一轮结果和n相同,那也不为快乐数.

```java
class Solution {
public boolean isHappy(int n) {
if (n <= 0) return false;
int sum = 0;
while (sum != n) {
while (n > 0) {
sum += Math.pow(n % 10 ,2);
n /= 10;
}
if (sum == 1) {
return true;
} else if (sum == 4) {
return false;
} else {
n = sum;
sum = 0;
}
}
return false;
}
}

// 递归
public boolean isHappy(int n) {
if (n <= 0) return false;
int sum = 0;
while (n > 0) {
sum += Math.pow(n % 10 ,2);
n /= 10;
}
if (sum == 1) {
return true;
} else if (sum == 4) {
return false;
} else {
return isHappy(sum);
}
}
```
39 changes: 39 additions & 0 deletions solution/0202.Happy Number/Solution.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

class Solution {
public boolean isHappy(int n) {
if (n <= 0) return false;
int sum = 0;
while (sum != n) {
while (n > 0) {
sum += Math.pow(n % 10, 2);
n /= 10;
}
if (sum == 1) {
return true;
} else if (sum == 4) {
return false;
} else {
n = sum;
sum = 0;
}
}
return false;
}

// 递归
public boolean isHappy2(int n) {
if (n <= 0) return false;
int sum = 0;
while (n > 0) {
sum += Math.pow(n % 10, 2);
n /= 10;
}
if (sum == 1) {
return true;
} else if (sum == 4) {
return false;
} else {
return isHappy2(sum);
}
}
}

AltStyle によって変換されたページ (->オリジナル) /