当前位置:网站首页>力扣202-快乐数——哈希集合
力扣202-快乐数——哈希集合
2022-08-09 04:53:00 【张怼怼√】
题目描述
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」 定义为:
对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
求解思路
对于一个,一共会出现三种情况:
最终得到1,是快乐数;
进入一个循环,但得不到1,不是一个快乐数;
会越来越大,接近无穷大。
- 所以我们将 n 每一步的数字都记录到 HashSet 中,不断地迭代,最后如果为1,则返回 True,反之则返回 False;
- 在循环的过程中,循环条件是 当前这个数组不为1,且没有在Set中出现过。
输入输出示例
代码
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(n != 1 && !set.contains(n)){
set.add(n);
n = getPower(n);
}
return n==1;
}
public int getPower(int n){
int res = 0;
while(n > 0){
int tem = n % 10;
res += tem * tem;
n = n / 10;
}
return res;
}
}
边栏推荐
猜你喜欢
软件测试的发展趋势
Masked AutoEncoder论文及实现
ceph create pool, map, delete exercises
【Harmony OS】【ARK UI】轻量级数据存储
Nacos源码安装
Cluster deployment using ceph-deploycep with 3 disks as dedicated osd
JS-DOM-对象的事件onload、匿名函数、this
Quantitative Genetics Heritability Calculation 2: Half Siblings and Full Siblings
2022 Security Officer-A Certificate Special Work Permit Exam Question Bank and Online Mock Exam
2022 High Voltage Electrician Exam Questions and Answers
随机推荐
如何剪裁svg并压缩
mysql内容不存在的报错
[MLT] Analysis of MLT Multimedia Framework Production and Consumption Architecture (2)
B. Arrays Sum
杰理之采用mix out eq 没有作用【篇】
mysql content does not exist error
uboot中board_init bi_arch_number在哪
MySQL: Implementation Principles of Submitted Read and Repeatable Read | MVCC (Multi-Version Concurrency Control) - Notes for Your Own Use
Faced with risk control, what should Amazon do when evaluating self-supporting accounts?
【Harmony OS】【ArkUI】ets开发 图形与动画绘制
【HMS core】【ML kit】机器学习服务常见问题FAQ
软件测试的方法详细介绍
【Harmony OS】【ARK UI】Public Event Module
【Harmony OS】【ARK UI】ETS 上下文基本操作
Nacos源码安装
【暑期每日一题】洛谷 P5724 【深基4.习5】求极差 / 最大跨度值
2022 High Voltage Electrician Exam Questions and Answers
P1163 银行贷款
2022年8月深圳产品经理认证招生简章(NPDP)
Masked AutoEncoder论文及实现