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,这个逻辑需要进一步调整。

相关推荐
gugucoding几秒前
25. 【C语言】二进制文件与随机读写
c语言·开发语言
北极星日淘2 分钟前
中古货品品相评级算法实战|Java权重计分实现标准化五级品相体系
开发语言·python
小巧的砖头29 分钟前
C#会重蹈覆辙吗?系列之2:反射及元数据的性能问题
开发语言·前端·c#
凯瑟琳.奥古斯特32 分钟前
力扣1009补码解法C++实现
开发语言·c++·算法·leetcode·职场和发展
KaMeidebaby36 分钟前
卡梅德生物技术快报|蛋白的叠氮基修饰:实操解析:核酸模板耦合蛋白的叠氮基修饰实现靶蛋白定点共价标记
前端·人工智能·物联网·算法·百度
2601_9636459237 分钟前
【2026最新】MATLAB教程(附安装包,非常详细)
开发语言·matlab·信息可视化
十月的皮皮1 小时前
C语言学习笔记20260706-栈的压入、弹出序列验证
c语言·笔记·学习
dddwjzx1 小时前
嵌入式Linux C应用编程入门——信号
linux·嵌入式
闲猫2 小时前
Python 虚拟环境 virtualenv & uvicorn 服务搭建 & FAstAPI 使用
开发语言·python
通信仿真爱好者2 小时前
第【60期】--大规模MIMO系统信号检测算法误码率比较 --matlab完整代码+参考文章
算法·matlab·mimo·信号检测