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;
}
相关推荐
一只侯子11 分钟前
Face AE Tuning
图像处理·笔记·学习·算法·计算机视觉
jianqiang.xue24 分钟前
别把 Scratch 当 “动画玩具”!图形化编程是算法思维的最佳启蒙
人工智能·算法·青少年编程·机器人·少儿编程
不许哈哈哈1 小时前
Python数据结构
数据结构·算法·排序算法
J***79392 小时前
后端在分布式系统中的数据分片
算法·哈希算法
Dream it possible!3 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树中第 K 小的元素(86_230_C++_中等)
c++·leetcode·面试
sin_hielo3 小时前
leetcode 2872
数据结构·算法·leetcode
dragoooon344 小时前
[优选算法专题八.分治-归并 ——NO.49 翻转对]
算法
玩转C语言和数据结构4 小时前
C语言编程入门攻略(最新学习路线,适合新手小白)
c语言·c语言入门·c语言下载·c语言知识点总结·c语言自学·c语言教程·c语言怎么学
AI科技星4 小时前
为什么宇宙无限大?
开发语言·数据结构·经验分享·线性代数·算法
Bona Sun4 小时前
单片机手搓掌上游戏机(十四)—pico运行fc模拟器之电路连接
c语言·c++·单片机·游戏机