当前位置:网站首页>202. Happy number
202. Happy number
2022-07-26 17:54:00 【Crazy boy】
subject : Write an algorithm to judge a number n Is it a happy number .
「 Happy number 」 Defined as :
For a positive integer , Replace the number with the sum of the squares of the numbers in each of its positions .
Then repeat the process until the number becomes 1, It could be Infinite loop But it doesn't change 1.
If this process The result is 1, So this number is the happy number .
If n yes Happy number Just go back to true ; No , Then return to false .
analysis :
The most important thing in this problem is to find the condition to end the cycle .
1)sum==1, End of cycle ,return true;
2)sum When repeated , End of cycle ,return false;
Code (java):
class Solution {
public boolean isHappy(int n) {
int sum =-1;
Set<Integer> set = new HashSet<>();
while(sum!=1){
if(sum != -1)n=sum;
sum =0;
while(n>0){
sum += (n%10)*(n%10);
n = n/10;
}
if(set.contains(sum))return false;
set.add(sum);
}
return true;
}
}边栏推荐
- Sequential storage structure of linear table -- sequential table
- 线性表的顺序存储结构——顺序表
- 树形dp问题
- 基本的SELECT语句
- uni-app
- [virtual machine data recovery] data recovery cases in which XenServer virtual machine is unavailable due to accidental power failure and virtual disk files are lost
- 重磅!《2022中国开源发展蓝皮书》正式发布
- ACL experiment demonstration (Huawei router device configuration)
- ACL实验演示(Huawei路由器设备配置)
- Mondriaans's dream (state compression DP)
猜你喜欢

【集训Day3】section

Spark data format unsafe row

图的遍历的定义以及深度优先搜索和广度优先搜索(一)
![[Day2] cinema ticket](/img/da/a206266b94d1579a18f761fff74ef8.png)
[Day2] cinema ticket

我们被一个 kong 的性能 bug 折腾了一个通宵

The user experience center of Analysys Qianfan bank was established to help upgrade the user experience of the banking industry

Click hijacking attack

Deep learning experiment: softmax realizes handwritten digit recognition

来吧开发者!不只为了 20 万奖金,试试用最好的“积木”来一场头脑风暴吧!

大咖访谈 | 开源对安全是双刃剑——《大教堂与集市》中文译本作者卫剑钒
随机推荐
Just this time! Talk about the technical solutions of distributed system in detail
Week 17 free intrusion pointer exercise - output maximum
Overview of the agenda of the keynote speech of apachecon Asia, an international celebrity vs a local open source star
硬件开发与市场产业
How to set IP for layer 2 management switches
数据库使用psql及jdbc进行远程连接,不定时自动断开的解决办法
Heavy! The 2022 China open source development blue book was officially released
10、 Implementation of parameter modification of parameter server
AI遮天传 ML-无监督学习
AI sky covering DL multilayer perceptron
【数字IC】深入浅出理解AXI-Lite协议
来吧开发者!不只为了 20 万奖金,试试用最好的“积木”来一场头脑风暴吧!
[training Day2] sculpture
OpenWrt之feeds.conf.default详解
2022河南萌新联赛第(三)场:河南大学
uni-app
Coscon'22 city / school / institution producer solicitation order
就这一次!详细聊聊分布式系统的那些技术方案
跨站点请求伪造(CSRF)
JS 函数作用域 变量声明提升 作用域链 不加var的变量,是全局变量