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;
}
相关推荐
算法鑫探24 分钟前
C语言入门:a和b 比大小
c语言·数据结构·算法·新人首发
不爱吃炸鸡柳40 分钟前
算法复杂度从入门到精通:时间与空间复杂度全解析
开发语言·c++·算法
拳里剑气1 小时前
C++算法:二分查找
c++·算法·二分查找·学习方法
黎阳之光1 小时前
去标签化定位时代:黎阳之光自研技术,可见即可定位,无感亦能解算
大数据·人工智能·算法·安全·数字孪生
一只小小的土拨鼠1 小时前
【国奖冲刺/全网首发】2026年第十四届“泰迪杯”A、B、C题完整解题思路、代码与高质量论文大合集
c语言·矩阵·数据挖掘
故事和你911 小时前
洛谷-算法1-7-搜索2
数据结构·c++·算法·leetcode·深度优先·动态规划·图论
炽烈小老头1 小时前
【每天学习一点算法 2026/094/14】分数到小数
学习·算法
_深海凉_1 小时前
LeetCode热题100-和为 K 的子数组
数据结构·算法
深紫色的三北六号1 小时前
仿大疆司空2面状航线生成——凸多边形区域航线生成算法详解
java·算法·无人机·大疆·航线规划