当前位置:网站首页>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;
}
};
边栏推荐
- 13 and OOM simulation
- How to start an NFT collection
- ModelWhale 云端运行 WRF 中尺度数值气象模式,随时随地即开即用的一体化工作流
- leetcode SVM
- [QT] Qt project demo: data is displayed on the ui interface, double-click the mouse to display specific information in a pop-up window
- 【Unity入门计划】基本概念(7)-Input Manager&Input类
- 常见分布式理论(CAP、BASE)和一致性协议(Gosssip、Raft)
- Difference and performance comparison between HAL and LL library of STM32
- 攻防世界----bug
- 破解数字化转型困局,企业分析协同场景案例解析
猜你喜欢

罗克韦尔AB PLC RSLogix5000中创建新项目、任务、程序和例程的具体方法和步骤

Fortinet产品导入AWS AMI操作文档

使用 PowerShell 将 Windows 转发事件导入 SQL Server

【Unity入门计划】基本概念(7)-Input Manager&Input类

DataGrip:非常好用的数据库工具,安装与使用教程,亮点介绍

技术干货|如何将 Pulsar 数据快速且无缝接入 Apache Doris

Spark entry learning-2

如何使用MATLAB绘制极坐标堆叠柱状图

Analysis of ffplay video playback principle

【Unity入门计划】基本概念(8)-瓦片地图 TileMap 02
随机推荐
Kubernetes 笔记 / 入门 / 生产环境 / 用部署工具安装 Kubernetes / 用 kubeadm 启动集群 / 安装 kubeadm
I am doing open source in Didi
20. Valid Parentheses
字典表(还需要输入2个字)
不可忽略!户外LED显示屏的特点及优势
简易网络传输方法
MySQL窗口函数
Convex Optimization of Optimal Power Flow (OPF) in Microgrids and DC Grids (Matlab Code Implementation)
袁小林:沃尔沃专注于出行的安全感,并且把它做到极致
mysql delete 执行报错:You can‘t specify target table ‘doctor_info‘ for update in FROM clause
DataGrip数据仓库工具
[Unity Getting Started Plan] Basic Concepts (8) - Tile Map TileMap 01
我在滴滴做开源
美国国防部更“青睐”光量子系统研究路线
红蓝对抗经验分享:CS免杀姿势
全新探险者以40万的产品击穿豪华SUV价格壁垒
Introduction to spark learning - 1
Kubernetes 笔记 / 目录
2021年数据泄露成本报告解读
Go Go 简单的很,标准库之 fmt 包的一键入门