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;
}
相关推荐
AI街潜水的八角3 分钟前
基于C++的决策树C4.5机器学习算法(不调包)
c++·算法·决策树·机器学习
白榆maple28 分钟前
(蓝桥杯C/C++)——基础算法(下)
算法
JSU_曾是此间年少32 分钟前
数据结构——线性表与链表
数据结构·c++·算法
sjsjs1139 分钟前
【数据结构-合法括号字符串】【hard】【拼多多面试题】力扣32. 最长有效括号
数据结构·leetcode
朱一头zcy1 小时前
C语言复习第9章 字符串/字符/内存函数
c语言
此生只爱蛋1 小时前
【手撕排序2】快速排序
c语言·c++·算法·排序算法
何曾参静谧2 小时前
「C/C++」C/C++ 指针篇 之 指针运算
c语言·开发语言·c++
咕咕吖2 小时前
对称二叉树(力扣101)
算法·leetcode·职场和发展
九圣残炎3 小时前
【从零开始的LeetCode-算法】1456. 定长子串中元音的最大数目
java·算法·leetcode
lulu_gh_yu3 小时前
数据结构之排序补充
c语言·开发语言·数据结构·c++·学习·算法·排序算法