当前位置:网站首页>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
边栏推荐
- 2022年流动式起重机司机考试题库模拟考试平台操作
- Sim Api User Guide(7)
- 利用多线程按顺序连续输出abc10次
- 《谷雨系列》空投
- 转:毛姆:阅读是一座随身携带的避难所
- Chapter 2 Oracle database in memory architecture (I) (im-2.1)
- Comparative analysis of meta universe from the dimension of knowledge dissemination
- DBA常用SQL语句(6)- 日常管理
- Classic routine: DP problem of a kind of string counting
- 杰理之系统事件有哪些【篇】
猜你喜欢

2022年上海市安全员C证考试题库及答案

Arm debugging (1): two methods to redirect printf to serial port in keil

C language: expression evaluation (integer promotion, arithmetic conversion...)

Planning and construction of industrial meta universe platform

Redis design and Implementation

failureForwardUrl与failureUrl

shell脚本免交互
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled]

Nine abilities of agile manufacturing in the era of meta universe

JUC concurrent programming 06 -- in-depth analysis of AQS source code of queue synchronizer
随机推荐
DBA common SQL statements (3) - cache, undo, index and wait events
Go语言实践模式 - 函数选项模式(Functional Options Pattern)
ansible 云计算 自动化 命令行精简版
【无标题】
实践六 Windows操作系统安全攻防
Career planning and implementation in the era of meta universe
Yarn资源调度器
Yarn核心参数配置
Function realization of printing page
Custom login failure handling
Formattime timestamp format conversion
JUC concurrent programming 09 -- source code analysis of condition implementation
ansible playbook语法和格式 自动化云计算
failureForwardUrl与failureUrl
解决VMware卸载后再安装出现的问题
深度选择器
Read LSTM (long short term memory)
CSP认证 202203-2 出行计划(多种解法)
DBA common SQL statements (5) - latch related
Art template template engine