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;
}
相关推荐
吹什么轩4 分钟前
数据结构复习:二叉搜索树
数据结构·算法
H.莓飛6 分钟前
【数据结构】堆
linux·数据结构·算法
纪念 22915 分钟前
C++算法(二)
开发语言·c++·算法
lie..24 分钟前
30天从零开始学AI应用开发(Day 16):Embedding 是什么?用人话讲明白“向量检索”
人工智能·算法·embedding
李永奉9 小时前
C语言-指针函数与函数指针及回调函数的使用
c语言·开发语言
杨丰玮4189 小时前
C语言基础知识(一)————各类符号的含义与输入输出库(stdio)
c语言·开发语言
水饺编程10 小时前
第1章,了解乌班图环境,使用浏览器和邮箱
c语言·汇编·ubuntu
朝朝辞暮i11 小时前
C++ 第 21 课:struct —— 把一组相关数据打包在一起
开发语言·c++·算法
青梅橘子皮11 小时前
Blue---二分算法(二分查找与二分答案)
算法
长河11 小时前
Java的GC(垃圾回收)中,标记无用对象的核心方法是可达性分析算法
java·jvm·算法