LeetCode //C - 202. Happy Number

202. Happy Number

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.
    Return true if n is a happy number, and false if not .

Example 1:

Input: n = 19
Output: true
Explanation:
1 2 + 9 2 = 82 1^2 + 9^2 = 82 12+92=82
8 2 + 2 2 = 68 8^2 + 2^2 = 68 82+22=68
6 2 + 8 2 = 100 6^2 + 8^2 = 100 62+82=100
1 2 + 0 2 + 0 2 = 1 1^2 + 0^2 + 0^2 = 1 12+02+02=1

Example 2:

Input: n = 2
Output: false

Constraints:

  • 1 < = n < = 2 31 − 1 1 <= n <= 2^{31} - 1 1<=n<=231−1

From: LeetCode

Link: 202. Happy Number


Solution:

Ideas:

Here, the sumOfSquares function calculates the sum of the squares of the digits of the given number. The isHappy function uses the Floyd's Tortoise and Hare (Cycle Detection) algorithm to detect if there is a loop in the sequence. If a cycle is detected, the number is not a happy number. If the sequence reaches 1, the number is a happy number.

Code:
c 复制代码
bool isHappy(int n) {
    int slow = n, fast = n; // Two pointers for cycle detection

    do {
        slow = sumOfSquares(slow); // Move slow one step
        fast = sumOfSquares(sumOfSquares(fast)); // Move fast two steps
    } while (slow != fast && fast != 1);

    return fast == 1;
}

int sumOfSquares(int n) {
    int sum = 0;
    while (n > 0) {
        int digit = n % 10;
        sum += digit * digit;
        n /= 10;
    }
    return sum;
}
相关推荐
Interview Aid11210 分钟前
Akuna OA 题目拆解|三题思路复盘
linux·运维·算法·面试·职场和发展
wabs66636 分钟前
关于栈【力扣150.逆波兰表达式求值的思考】
数据结构·c++·算法·leetcode··代码随想录
ZGi.ai37 分钟前
ZGI 父子分块:连接检索片段与完整上下文
人工智能·算法·知识库·企业ai·zgi·父子分块
IT毕设实战小研42 分钟前
基于大数据的二手车数据分析与预测
java·大数据·后端·爬虫·python·算法·课程设计
Allen_LVyingbo1 小时前
医疗AI可扩展网格信息系统中网格计算技术的智能优化
大数据·人工智能·python·算法·机器学习·django·健康医疗
WBluuue1 小时前
数据结构与算法:带权并查集
数据结构·c++·算法
熊猫_豆豆1 小时前
黑洞的粒子产生(霍金1975年论文)第二部分
人工智能·数学·算法·机器学习·量子力学·大学物理·黑洞
jay神1 小时前
本科深度学习需要从零开始训练模型吗?
人工智能·深度学习·算法·机器学习·计算机视觉
二级小助手1 小时前
C语言二级操作题高频真题精解与大题代码模板
c语言·计算机二级·二级c语言·c语言操作题·c语言真题·c语言大题
Feynman’s boom2 小时前
PDF解析复盘
数据库·人工智能·算法·pdf解析