当前位置:网站首页>Leetcode 202. happy number (2022.07.21)
Leetcode 202. happy number (2022.07.21)
2022-07-22 14:55:00 【ChaoYue_ miku】
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 .
Example 1:
Input :n = 19
Output :true
explain :
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input :n = 2
Output :false
Tips :
1 <= n <= 231 - 1
source : Power button (LeetCode)
link :https://leetcode.cn/problems/happy-number
Method 1 : Fast and slow pointer method
C++ Submission :
class Solution {
public:
int bitSquareSum(int n){
int sum = 0;
while(n > 0){
int bit = n%10;
sum += bit*bit;
n = n/10;
}
return sum;
}
bool isHappy(int n) {
int slow = n,fast = n;
do{
slow = bitSquareSum(slow);
fast = bitSquareSum(fast);
fast = bitSquareSum(fast);
} while(slow != fast);
return slow == 1;
}
};
边栏推荐
- 顺序表与链表(顺序表)
- HCIA-R&S自用笔记(16)DR与BDR、OSPF度量值、OSPF 配置、OSPF综合实验(认证+缺省路由发布)
- Hcia-r & s self use notes (17) OSPF experiment and routing comprehensive experiment
- HCIA-R&S自用笔记(15)OSPF基础、OSPF核心工作流程、OSPF数据包类型、OSPF邻居建立条件及过程
- 2022.7.11-7.17 AI行业周刊(第106期):竭尽全力,努力就好
- HCIA-R&S自用笔记(17)OSPF实验与路由综合实验
- Matlab基本语法(二)
- 2022 melting welding and thermal cutting operation certificate examination question bank simulated examination platform operation
- 【Harmony OS】【ARK UI】【Demo】加载动画实现
- Mysql語句的RegExp的用法與案例
猜你喜欢
【Try to Hack】Syn Flood和CC攻击
在线问题反馈模块实战(十):实现图片预览功能
IDM下载器软件激活序列号错误如何解决?
OS7-资源的死锁
【MySQL系列】MySQL表的增删改查(基础)
[HMS core] [FAQ] [account kit] typical problem set 2
[MySQL series] addition, deletion, modification and query of MySQL tables (Advanced)
解决win10莫名其妙重启问题
[AGC] build service 1- cloud function example
Troubleshooting - find the loop through lldp information (take H3C S5100 as an example)
随机推荐
687. Longest same value path ●●
IDM下载器软件激活序列号错误如何解决?
1382. 将二叉搜索树变平衡 ●●
实操演示:如何用 ONES 制定 Scrum 迭代计划?
[open source diary] dormitory power-off automatic light off equipment (II)
OS09- AutoSAR OS事件机制和实例解析
Network analysis -- making difference on the search set
HCIA-R&S自用笔记(14)RIP协议
【 série mysql】 "résoudre une fois pour toutes le problème de l'erreur" insérer des données chinoises "dans MySQL
Mysql语句的RegExp的用法与案例
HCIA-R&S自用笔记(17)OSPF实验与路由综合实验
Practical demonstration: how to make a scrum iteration plan with ones?
我的创作纪念日
pmp考试如何复习
6、学习MySQL 删除数据库
【Harmony OS】【ARK UI】【Demo】加载动画实现
y73.第四章 Prometheus大厂监控体系及实战 -- blackbox exporter安装和grafana安装(四)
【HMS Core】【FAQ】运动健康、音频编辑、华为帐号服务 典型问题合集7
【开源日记】宿舍断电自动关灯设备(二)
2022 melting welding and thermal cutting operation certificate examination question bank simulated examination platform operation