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;
}
相关推荐
颜酱2 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_736919102 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi9878382 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
DuHz2 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女2 小时前
TRSV优化2
算法
代码游侠3 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_763472463 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy4 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异4 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_706653234 小时前
分布式系统安全通信
开发语言·c++·算法