C语言刷题 LeetCode 30天挑战 (二)快慢指针法

Write an algorithm to determine if a number 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 thesquares of its digits,

and repeat the process until the number equals 1 (where it will stay, or it loops endlessly in a cycle which does notinclude 1. Those numbers for which this process ends in 1 are happy numbers.

Input:19

Output:true

Explanation

1^2 + 9^2 = 82

8^2 + 2^2 = 68

6^2 + 8^2 = 100

1^2 + 0^2 + 0^2 = 1

循环检测 是不是在1轮回 快慢指针~

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define DEBUG

int next_n(int n){
    int r=0;
    while(n != 0){
        int d = n % 10;
        n /= 10;
        r += d*d;
    }
    return r;
}

bool contains(int *history,int size,int n){
    for(int i=0; i<size ;++i){
        if(history[i] == n){
            return true;
        }
    }
    return false;
}

bool ishappy(int n){
    int slow=n;
    int fast=n;
    
    do{
        slow = next_n(slow);
        fast = next_n(next_n(fast));
#ifdef DEBUG
        printf("%d %d \n",slow,fast);
#endif
    } while (slow != fast);

    return false;
}

int main()
{
    ishappy(19);
    if(ishappy)
        printf("yes");
    else printf("no");
    return 0;
} 

slow 和 fast 都初始化为输入的数字 n。

slow 每次移动一步,即计算一次数字的平方和;fast 每次移动两步,计算两次平方和。

在循环中,如果 slow == fast,则表示数字进入了循环,不会到达 1。

但是,在这段代码中,无论循环如何执行,最后的结果总是返回 false,这个逻辑需要进一步调整。

相关推荐
JAVA面经实录91718 小时前
Java企业级工程化·终极完整版背诵手册(无遗漏、全覆盖、面试+落地通用)
java·开发语言·面试
HHFQ18 小时前
在 systemd 场景下的 CPU 限制方式
linux
道清茗18 小时前
【RH294知识点汇总】第 9 章 《 自动执行 Linux 管理任务 》常见问题
linux·运维·服务器
山羊硬件Time18 小时前
自动化管理Linux的好工具:shell script
linux·嵌入式硬件·硬件工程师·基带工程·硬件开发
王老师青少年编程18 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
周杰伦fans19 小时前
AutoCAD .NET 二次开发:深入理解 EntityJig 的工作原理与正确实现
开发语言·.net
叼烟扛炮19 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说19 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wj30558537819 小时前
Codex + Git 开发环境配置指南(WSL版)
linux·运维·git
星马梦缘20 小时前
如何切换window-ubuntu双系统【方案二】
linux·运维·ubuntu