当前位置:网站首页>力扣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;
}
}边栏推荐
- 杰理之一拖二 另一台手机超距 通话会无声【篇】
- How to trim svg and compress
- 抖音直播间带货最新玩法和运营技巧
- 2022-08-07 反思
- 【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
- Base64编码和图片转化
- ceph create pool, map, delete exercises
- 【HMS Core】【FAQ】【AR Engine】AR Engine常见问题合集
- How to choose an APS system, it is necessary to clarify these seven key factors
- 【日常训练--腾讯精选50】7. 整数反转
猜你喜欢

Introduction to JVM garbage collection mechanism

软件测试的方法详细介绍

Faced with risk control, what should Amazon do when evaluating self-supporting accounts?

LN论文、五种归一化原理和实现

杰理之ANC OFF语音没有作用【篇】
![could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarExcept](/img/00/328e4c296c00929140c9aff3bb896e.png)
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarExcept

Cluster deployment using ceph-deploycep with 3 disks as dedicated osd

Nacos源码安装

JS-全局dom对象的使用---使用htm样式和js函数动作的完全分离

【Harmony OS】【ARK UI】Date 基本操作
随机推荐
TASSEL software imports plink format file error
还不了解什么是商业智能(BI)?看完这篇文章就懂了
MySQL: redo log log - notes for personal use
leetcode:316. 去除重复字母
php uses phpoffice/phpspreadsheet to import and export excel tables
TCP/IP协议中分包与重组原理介绍、分片偏移量的计算方法、IPv4报文格式
2022 Security Officer-B Certificate Exam Practice Questions and Online Mock Exam
杰理之电话打入,远端听不到声音【篇】
OKR management process, how to implement effective dialogue, using the CFR feedback and recognition?
【Harmony OS】【ARK UI】ETS 上下文基本操作
杰理之SD卡切回蓝牙没有作用【篇】
【日常训练--腾讯精选50】7. 整数反转
【Harmony OS】【ARK UI】Public Event Module
HP路由器和交换机日志分析
【Harmony OS】【FAQ】鸿蒙问题合集1
MySQL---performance schema
php使用phpoffice/phpspreadsheet导入导出excel表格
I.MX6U-ALPHA开发板(高精度定时器)
Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection
程序设计6大原则