0

#yyds干货盘点# leetcode算法题:快乐数

 2 years ago
source link: https://blog.51cto.com/u_13321676/5558248
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# leetcode算法题:快乐数

原创

灰太狼_cxh 2022-08-09 11:05:16 博主文章分类:leetcode ©著作权

文章标签 代码实现 无限循环 文章分类 Java 编程语言 阅读数185

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

「快乐数」 定义为:

对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。

然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。

如果这个过程 结果为 1,那么这个数就是快乐数。

如果 n 是 快乐数 就返回 true ;不是,则返回 false 。

输入:n = 19

输出:true

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

输入:n = 2

输出:false

代码实现:

class Solution {
private int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}

public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = getNext(n);
}
return n == 1;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK