当前位置:网站首页>leetcode:202. 快乐数
leetcode:202. 快乐数
2022-08-03 16:05:00 【OceanStar的学习笔记】
题目来源
题目描述

题目解析
模拟
class Solution {
public:
bool isHappy(int n) {
std::set<int> set;
set.insert(n);
while (n != 1){
int sum = 0;
while (n != 0){
// 2
sum += std::pow(n % 10, 2); // ans = 4
n = n / 10; // 0
}
if(set.count(sum)){
return false;
}
set.insert(sum);
n = sum;
}
return true;
}
};
快慢指针

怎么检测环呢?快慢指针
class Solution {
int getNext(int n){
int sum = 0;
while(n > 0)
{
int bit = n % 10;
sum += bit * bit;
n = n / 10;
}
return sum;
}
public:
bool isHappy(int n) {
int slow = n, fast = n;
do {
slow = getNext(slow);
fast = getNext(getNext(fast));
}while (fast != slow);
return fast == 1;
}
};
边栏推荐
猜你喜欢

STM32的HAL和LL库区别和性能对比

Introduction to spark learning - 1

【Unity入门计划】制作RubyAdventure01-玩家的创建&移动

《安富莱嵌入式周报》第276期:2022.07.25--2022.07.31

全新探险者以40万的产品击穿豪华SUV价格壁垒

世界顶级级架构师编写2580页DDD领域驱动设计笔记,属实有牌面

To add digital wings to education, NetEase Yunxin released the overall solution of "Internet + Education"

MATLAB | 七夕节快到了,还不给朋友安排上这个咕呱小青蛙?

Yii2安装遇到Loading composer repositories with package information

Small Tools(4) 整合Seata1.5.2分布式事务
随机推荐
Awesome!Coroutines are finally here!Thread is about to be in the past
Leetcode76. 最小覆盖子串
JD6606SP5_JD6606SSP_JD6606SASP_JD6621W7百盛新纪元授权代理商
MySQL性能优化_小表驱动大表
Analysis of ffplay video playback principle
下午见!2022京东云数据库新品发布会
[QT] Qt project demo: data is displayed on the ui interface, double-click the mouse to display specific information in a pop-up window
I am doing open source in Didi
window.open不显示favicon.icon
请问大家,MySQL全量怎么样可以提高性能呢?我这里瓶颈是在Source上,在不增加并行度的情况下,
vector类
【QT】Qt项目demo:数据在ui界面上显示,鼠标双击可弹窗显示具体信息
【Unity入门计划】基本概念(6)-精灵渲染器 Sprite Renderer
Research on power flow in DC microgrid based on Newton's method (Matlab code implementation)
MySQL窗口函数 PARTITION BY()函数介绍
1、实例开启无锁表结构变更以后,在任务编排中通过“单实例SQL”节点进行的结构变更,是优先采用无锁表
MySQL查询语法
Tolstoy: There are only two misfortunes in life
如何分析周活跃率?
spark入门学习-2