当前位置:网站首页>代码随想录笔记_哈希_202 快乐数
代码随想录笔记_哈希_202 快乐数
2022-07-30 08:42:00 【Erik_Won】
代码随想录笔记_哈希表
代码随想录二刷笔记记录
LC 202. 快乐数
题目
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」 定义为:
对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
示例 1:
输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
示例 2:
输入:n = 2
输出:false
思路分析
由题目说的可能无限循环,但始终变不到 1,因此,我们可知 sum 是会重复出现的,此为解题的关键点,在sum重复出现时,我们就可以断定这个数并非快乐数。否则一定能变到 1。
代码实现
完整代码实现
写法1
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
int sum = 0;
while (true){
sum = getSum(n);
if (sum == 1) return true;
//进入无限循环,判断 HashSet中的sum 是否重复
if (record.contains(sum)){
//重复了,返回 false
return false;
}else {
//没有重复,记录出现的sum
record.add(sum);
}
n = sum;//更新 n 的值
}
}
/** * 定义一个计算 Sum 的函数 */
public int getSum(int n){
int sum = 0;
while (n > 0){
int temp = n%10;//取 个位十位百位
sum += temp*temp;
n = n/10;
}
return sum;
}
简化写法
public boolean isHappy(int n) {
//简化写法
while(n != 1 ){
//&& !record.contains(n)
//将判断条件融合了,当 n == 1 或者是 sum 重复的时候,都会退出循环,判断 n 是否 = 1
record.add(n);//记录 sum 的值,此时 n 即是 sum
n = getSum(n);//更新 n 的值
if(record.contains(n)){
return false;
}
}
return n == 1;
}
/** * 定义一个计算 Sum 的函数 */
public int getSum(int n){
int sum = 0;
while (n > 0){
int temp = n%10;//取 个位十位百位
sum += temp*temp;
n = n/10;
}
return sum;
}
边栏推荐
- Functional Interfaces & Lambda Expressions - Simple Application Notes
- Concise Notes on Integrals - Types of Curve Integrals of the First Kind
- 涛思 TDengine 2.6+优化参数
- PyQt5快速开发与实战 8.1 窗口风格
- 虚幻引擎图文笔记:could not be compiled. Try rebuilding from source manually.问题的解决
- Is R&D moving to FAE (Field Application Engineer), is it moving away from technology?Is there a future?
- 20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
- The difference between DDR, GDDR, QDR
- 嘉为鲸翼·多云管理平台荣获信通院可信云技术服务最佳实践
- [Fun BLDC series with zero basics] Taking GD32F30x as an example, the timer related functions are explained in detail
猜你喜欢
随机推荐
ClickHouse
Use the R language to read the csv file into a data frame, and then view the properties of each column.
瑞吉外卖项目(五) 菜品管理业务开发
深入浅出零钱兑换问题——背包问题的套壳
Network/Information Security Top Journal and Related Journals Conference
读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
【无标题】
leetcode-990:等式方程的可满足性
如何避免CMDB沦为数据孤岛?
Unity性能分析 Unity Profile性能分析工具
test3
虚幻引擎图文笔记:could not be compiled. Try rebuilding from source manually.问题的解决
stugc_paper
C language classic practice questions (3) - "Hanoi Tower (Hanoi)"
Kotlin value class - value class
HCIP --- MPLS VPN实验
Farthest Point Sampling - D-FPS vs F-FPS
最远点采样 — D-FPS与F-FPS
【科普向】5G核心网架构和关键技术
Integral Special Notes-Three Formulas for Curve Area Integral









