当前位置:网站首页>代码随想录笔记_哈希_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;
}
边栏推荐
猜你喜欢

SRAM与DRAM的区别

Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上

One article to understand twenty kinds of switching power supply topologies

02-课程发布

树莓派_烧写Raspberry官方镜像系统

STM8L_库函数-模板搭建

20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission

剖析SGI STL空间配置器(一 、辅助接口函数)

opencv可以有多有趣

Jetpack Compose 从入门到入门(八)
随机推荐
Access to display the data
Functional Interfaces & Lambda Expressions - Simple Application Notes
仿牛客网项目第二章:开发社区登录模块(详细步骤和思路)
利用R语言读取csv文件入一个数据框,然后查看各列的属性。
Unity性能分析 Unity Profile性能分析工具
读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
Using IN in MySQL will not go through index analysis and solutions
Integral Special Notes-Three Formulas for Curve Area Integral
Unity performance analysis Unity Profile performance analysis tool
ant-design form form verification upload component (with personal packaged upload component)
Flutter 环境变量配置和flutter doctor中的错误解决
2022杭电多校第一场
Two solutions for Excel xlsx file not supported
Dynamic Lead Time Promising
Use the R language to read the csv file into a data frame, and then view the properties of each column.
342 · 山谷序列
电源完整性的去耦和层间耦合电容
积分专题笔记-积分的定义
剖析SGI STL空间配置器(空间配置器的重要性和重要成员及函数)
电源完整性基础知识