当前位置:网站首页>20220531数学:快乐数
20220531数学:快乐数
2022-07-03 09:20:00 【丿SeeYouAgain】
题目描述:编写一个算法来判断一个数 n 是不是快乐数。
快乐数定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
编码实现:
public static boolean isHappy(int n) {
if (n == 1) {
return true;
} else {
Set<Integer> set = new HashSet<>();
while (n != 1) {
int temp = n, sum = 0;
while (temp >= 10) {
int mod = temp % 10;
temp /= 10;
sum += mod * mod;
}
sum += temp * temp;
if (!set.add(sum)) {
return false;
}
n = sum;
}
}
return true;
}
边栏推荐
- When the reference is assigned to auto
- openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
- CV learning notes - camera model (Euclidean transformation and affine transformation)
- 2. Elment UI date selector formatting problem
- 01 business structure of imitation station B project
- Tensorflow2.0 save model
- (2)接口中新增的方法
- 01仿B站项目业务架构
- [combinatorics] combinatorial existence theorem (three combinatorial existence theorems | finite poset decomposition theorem | Ramsey theorem | existence theorem of different representative systems |
- Leetcode - 1670 design front, middle and rear queues (Design - two double ended queues)
猜你喜欢
Yocto Technology Sharing Phase 4: Custom add package support
LeetCode - 919. 完全二叉树插入器 (数组)
LeetCode - 900. RLE 迭代器
Opencv Harris corner detection
Yocto technology sharing phase IV: customize and add software package support
MySQL root user needs sudo login
Opencv image rotation
Swing transformer details-2
My notes on intelligent charging pile development (II): overview of system hardware circuit design
Leetcode interview question 17.20 Continuous median (large top pile + small top pile)
随机推荐
Replace the files under the folder with sed
Opencv notes 20 PCA
2021-10-28
LeetCode - 1670 设计前中后队列(设计 - 两个双端队列)
Windows下MySQL的安装和删除
CV learning notes - BP neural network training example (including detailed calculation process and formula derivation)
LeetCode - 5 最长回文子串
Vscode markdown export PDF error
2020-08-23
The underlying principle of vector
Gpiof6, 7, 8 configuration
01仿B站项目业务架构
2.Elment Ui 日期选择器 格式化问题
openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
[combinatorics] combinatorial existence theorem (three combinatorial existence theorems | finite poset decomposition theorem | Ramsey theorem | existence theorem of different representative systems |
My openwrt learning notes (V): choice of openwrt development hardware platform - mt7688
Leetcode 300 最长上升子序列
Do you understand automatic packing and unpacking? What is the principle?
el-table X轴方向(横向)滚动条默认滑到右边
Serial communication based on 51 single chip microcomputer