当前位置:网站首页>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
边栏推荐
- 第三章 启用和调整IM列存储的大小(IM-3.1)
- LeetCode 1249. Minimum Remove to Make Valid Parentheses - FB高频题1
- Juc并发编程06——深入剖析队列同步器AQS源码
- [COCI] Vje š TICA (subset DP)
- Operation of 2022 tea artist (primary) test question simulation test platform
- Pyqt5 and communication
- [CF 1425d] danger of mad snakes
- Prefix sum of integral function -- Du Jiao sieve
- Career planning and implementation in the era of meta universe
- 构建元宇宙时代敏捷制造的九种能力
猜你喜欢
2022年流动式起重机司机考试题库模拟考试平台操作
Zhengda international explains what the Dow Jones industrial index is?
《谷雨系列》空投
Failureforwardurl and failureurl
JUC concurrent programming 06 -- in-depth analysis of AQS source code of queue synchronizer
【无标题】
Juc并发编程07——公平锁真的公平吗(源码剖析)
Arm debugging (1): two methods to redirect printf to serial port in keil
Juc并发编程09——Condition实现源码分析
Depth selector
随机推荐
Juc并发编程07——公平锁真的公平吗(源码剖析)
MapReduce核心和基础Demo
[codeforces - 208e] blood cousins
转:毛姆:阅读是一座随身携带的避难所
Exercise questions and simulation test of refrigeration and air conditioning equipment operation test in 2022
Common DBA SQL statements (4) - Top SQL
Realize data value through streaming data integration (2)
Rain produces hundreds of valleys, and all things grow
Go语言实践模式 - 函数选项模式(Functional Options Pattern)
杰理之更准确地确定异常地址【篇】
元宇宙时代的职业规划与执行
Chapter II in memory architecture (im-2.2)
【无标题】
DBA common SQL statements (5) - latch related
通过流式数据集成实现数据价值(5)- 流分析
Sim Api User Guide(5)
Ansible cloud computing automation
【无标题】
打印页面的功能实现
Configuration of LNMP