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;
}
相关推荐
Felven15 分钟前
A. Everybody Likes Good Arrays!
数据结构·算法
小智学长 | 嵌入式1 小时前
单片机-89C51部分:4、固件烧录
c语言·单片机·嵌入式硬件
AI_RSER1 小时前
基于 Google Earth Engine 的南京江宁区土地利用分类(K-Means 聚类)
算法·机器学习·分类·kmeans·聚类·遥感·gee
Small踢倒coffee_氕氘氚1 小时前
是否应该禁止危险运动论文
经验分享·笔记·算法·灌灌灌灌
simple_whu2 小时前
C语言标准库函数setlocale用法详解
c语言
京东云开发者3 小时前
行稳、致远 | 技术驱动下的思考感悟
算法
Dignity_呱3 小时前
记一次手撕算法面试
前端·算法·面试
CodeJourney.3 小时前
深度探索:DeepSeek赋能WPS图表绘制
数据库·人工智能·算法·信息可视化·excel
陈奕昆3 小时前
6.1腾讯技术岗2025面试趋势前瞻:大模型、云原生与安全隐私新动向
算法·安全·云原生·面试·腾讯
ゞ 正在缓冲99%…3 小时前
leetcode66.加一
java·数据结构·算法