导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-202.Happy Number

题目

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: 19 is a happy number

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

翻译

编写算法判断一个数字是否“开心”。
开心数可以被以下过程定义:从任意一个正整数开始,将数字替换为其各位的平方和,不断重复该过程,直到数字为1(它将保持这个结果),或者无限循环为不包括1的结果。那些可以以1结束的数字称为开心数。
例如:19是一个开心数
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

以2为例:2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4
可知,只要在变换路径中出现非1的重复数字,即为非开心数,出现1则为开心数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public boolean isHappy(int n) {
if (n <= 0)
return false;
Set<Integer> process = new HashSet<Integer>();
while (n != 1) {
n = getSquareSum(n);
if (process.contains(n))
return false;
process.add(n);
}
return true;
}

public int getSquareSum(int n) {
int sum = 0;
while (n != 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
}