[LeetCode] Happy Number

Well, no matter whether the number is happy or not, its sum-of-squared-digits sequance has a cycle. Well, do you still remember the algorithm for detecting cycles in linked lists? Yeah, use a fast and a slow pointer. That's also applicable to this problem.

The code is as follows (idea from here).

复制代码
 1 class Solution {
 2 public:
 3     bool isHappy(int n) {
 4         int slow = n, fast = n;
 5         do {
 6             slow = squareDigits(slow);
 7             fast = squareDigits(squareDigits(fast));
 8         } while (slow != fast);
 9         return fast == 1;
10     }
11 private:
12     int squareDigits(int n) {
13         int sq = 0;
14         while (n) {
15             sq += (n % 10) * (n % 10);
16             n /= 10;
17         }
18         return sq;
19     }
20 };
复制代码

 

posted @   jianchao-li  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
点击右上角即可分享
微信分享提示