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;
}
相关推荐
Tandy12356_8 分钟前
手写TCP/IP协议栈——TCP结构定义与基本接口实现
c语言·网络·c++·网络协议·tcp/ip·计算机网络
ghie909012 分钟前
使用直接节点积分法进行无网格法2D悬臂梁计算
算法
Helibo4416 分钟前
2025年12月gesp3级题解
数据结构·c++·算法
p&f°19 分钟前
垃圾回收两种算法
java·jvm·算法
benjiangliu20 分钟前
STM32教程-02-STM32复习C语言
c语言·stm32·嵌入式硬件
点云SLAM27 分钟前
点云配准算法之- GICP算法点云配准概率模型推导和最大似然求解(MLE)
算法·机器人·slam·点云配准·最大似然估计·点云数据处理·gicp算法
曹轲恒29 分钟前
双栈实现队列/双队列实现栈
算法
AI科技星35 分钟前
张祥前统一场论电荷定义方程分析报告
开发语言·经验分享·线性代数·算法·数学建模
Swift社区1 小时前
LeetCode 460 - LFU 缓存
算法·leetcode·缓存
潇氡1 小时前
C语言“指针变量“在初始化和做函数参数时的注意事项
c语言