当前位置:网站首页>力扣刷题.快乐数
力扣刷题.快乐数
2022-07-31 05:17:00 【旺仔 小馒头】
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」 定义为:
对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
示例 1:
输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
示例 2:
输入:n = 2
输出:false
思路
1. 这题咋一看像是个数学题,而且看到循环两个字,大家一定会想到用递归,但是这是无限循环,潜在意思其实是会出现相同的数,既然会出现相同的数再往后进行判断就没有必要了。这个思路这对解题很重要。
2. 当我们遇到了要快速判断一个元素是否重复出现集合里的时候,需要我们快速想到哈希,这道题使用hash来判断sum是否重复出现吗,如果出现了直接返回false就好了,否则就一直循环下去到sum==1 为止
3. 首先需要写一个函数用来求n各个位置上的数的平方和,我们可以通过反复取余求每个位置上的数,并且一次次除10,去除掉已经求过平方的数,最后相加即可
代码如下:
class Solution {
public:
// 取数值各个位上的单数平方之和
int getSum(int n){
int sum = 0;
while (n){
sum += (n%10) * (n%10);
n = n/10;
}
return sum;
}
bool isHappy(int n) {
if(sum == 1)
return true;
int sum = getSum(n);
unordered_map<int,int> s;
while (sum != 1){
s[sum]++;
// 如果这个sum曾经出现过,说明已经陷入了无限循环了,立刻return false
if (s[sum] > 1)
return false;
sum = getSum(sum);
}
return true;
}
};边栏推荐
- Three methods of accessing image pixels in opencv
- Phospholipids-Polyethylene Glycol-Active Esters for Scientific Research DSPE-PEG-NHS CAS: 1445723-73-8
- Numpy常用函数
- 科学研究用磷脂-聚乙二醇-活性酯 DSPE-PEG-NHS CAS:1445723-73-8
- Learning and understanding of ROS service programming
- Detailed explanation of mysql transaction principle
- 钉钉H5微应用免登鉴权
- Pytorch学习笔记7——处理多维特征的输入
- cocos2d-x-3.2 create project method
- Getting Started with MySQL: The Case Statement Works Well
猜你喜欢

pytorch模型微调finetuning训练image_dog(kaggle)

Cholesterol-PEG-Thiol CLS-PEG-SH Cholesterol-Polyethylene Glycol-Sulfhydryl

pyspark.ml feature transformation module

CAS:1403744-37-5 DSPE-PEG-FA 科研实验用磷脂-聚乙二醇-叶酸

【Rhapsody学习笔记】3:Dishwasher

超详细!!!让你通透数组!!!初学复习不迷路!!

2021-09-30

MySQL free installation download and configuration tutorial

Picture-in-Picture API in the browser

DSPE-PEG-Azide DSPE-PED-N3 磷脂-聚乙二醇-叠氮脂质PFG
随机推荐
DSPE-PEG-Thiol DSPE-PEG-SH 磷脂-聚乙二醇-巯基脂质体制备用
学习JDBC之获取数据库连接的方式
MW:3400 4-Arm PEG-DSPE 四臂-聚乙二醇-磷脂一种饱和的18碳磷脂
Pytorch常用函数
DSPE-PEG-Biotin, CAS: 385437-57-0, phospholipid-polyethylene glycol-biotin prolongs circulating half-life
会话和饼干,令牌
pytorch模型微调finetuning训练image_dog(kaggle)
CLS-PEG-FITC Fluorescein-PEG-CLS 胆固醇-聚乙二醇-荧光素简介
MySQL 出现 The table is full 的解决方法
UR3机器人运动学分析之逆运动学分析
wangeditor编辑器内容传至后台服务器存储
The content of the wangeditor editor is transferred to the background server for storage
变分自编码器VAE实现MNIST数据集生成by Pytorch
Detailed explanation of mysql transaction principle
IDEA overview and installation and debugging
The solution to the IDEA console not being able to enter information
box-shadow related properties
Picture-in-Picture API in the browser
自己设置的私密文件,在哪找
解决background-size:cover时图片铺满但显示不完整?