当前位置:网站首页>202、快乐数
202、快乐数
2022-04-23 10:11:00 【Popuessing's Jersey】
题目:
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
思路:
将每次计算的sum记录下来,如果出现重复的sum值就可以判断无法得到快乐数,如果没有重复的sum值,那么说明这个计算会一直进行下去直到找到sum=1;
public class Kuaileshu {
//取各位数的单数平方的和
public int getSum(int n){
int sum = 0;
while(n>0){
sum +=(n%10)*(n%10);
n/=10;
}
return sum;
}
public boolean isHappy(int n){
Set<Integer> record = new HashSet<>();
//如果平方的和不等于1并且集合中不存在平方和
//就将本次平方的和存入集合中
while( n!= 1 && !record.contains(n)){
record.add(n);
n = getSum(n);
}
return n==1;
}
public static void main(String[] args) {
Kuaileshu kuaileshu = new Kuaileshu();
boolean res = kuaileshu.isHappy(19);
System.out.println(res);
}
}
输出结果:
True
版权声明
本文为[Popuessing's Jersey]所创,转载请带上原文链接,感谢
https://blog.csdn.net/CoCo629vanilla/article/details/121477243
边栏推荐
- Nvidia最新三维重建技术Instant-ngp初探
- Function realization of printing page
- Common DBA SQL statements (4) - Top SQL
- PHP two-dimensional array specifies that the elements are added after they are equal, otherwise new
- CSP certification 202203-2 travel plan (multiple solutions)
- 第一章 Oracle Database In-Memory 相关概念(续)(IM-1.2)
- 2022年制冷与空调设备运行操作考试练习题及模拟考试
- 通过流式数据集成实现数据价值(4)-流数据管道
- Go语言实践模式 - 函数选项模式(Functional Options Pattern)
- Sim Api User Guide(5)
猜你喜欢
第120章 SQL函数 ROUND
[untitled]
Question bank and answers of Shanghai safety officer C certificate examination in 2022
The central control learning infrared remote control module supports network and serial port control
Depth selector
【无标题】
Sim Api User Guide(5)
2022年上海市安全员C证考试题库及答案
Examination questions and answers of the third batch (main person in charge) of Guangdong safety officer a certificate in 2022
Shell script interaction free
随机推荐
Ansible cloud computing automation
Longest common front string
LeetCode-608. 树节点
Depth selector
2022年制冷与空调设备运行操作考试练习题及模拟考试
工业元宇宙平台规划与建设
打印页面的功能实现
A concise course of fast Fourier transform FFT
2022 mobile crane driver test question bank simulation test platform operation
0704、ansible----01
2022年上海市安全员C证考试题库及答案
中职网络安全2022国赛之CVE-2019-0708漏洞利用
Solve the problem of installing VMware after uninstalling
1D / 1D dynamic programming learning summary
shell脚本免交互
杰理之AES能256bit吗【篇】
Juc并发编程09——Condition实现源码分析
[Niuke practice match 68] fans of Niuniu (matrix fast power cycle matrix optimization)
Go语言实践模式 - 函数选项模式(Functional Options Pattern)
Sim Api User Guide(5)