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

相关推荐
Tisfy4 分钟前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
无小道7 分钟前
C/C++——tuple小记
c++·tuple
小O的算法实验室8 分钟前
IEEE TEVC,基于K-means与DQN辅助元启发式算法的多目标两栖无人艇调度模型
算法·kmeans·启发式算法
zcmodeltech20 分钟前
冷链物流沙盘模型控制系统设计——基于STM32与Modbus RTU的冷藏车、冷库全流程动态展示方案
数据结构·stm32·单片机·嵌入式硬件·物联网·能源
cjp56021 分钟前
011. UG二次开发,UG管道通讯服务器与wpf客户端通讯
linux·运维·服务器
mmmmath_322 分钟前
LeetCode.350.两个数组的交集II
算法
智闲电子设计24 分钟前
RS485 总线实战:终端电阻、差分信号、半双工方向控制,工程里最容易翻车的几处
c语言·stm32·单片机·嵌入式硬件
Ivanqhz29 分钟前
图是“拓扑 + 类型 + 形状“的世界
算法·决策树·机器学习·php·集成学习
上官唐云30 分钟前
2024届本科 | C++ Linux服务端开发求职:从嵌入式到底层服务端的技术之路(附开源项目+简历)
linux·c++·开源·求职招聘
云雀衔光35 分钟前
Java Spring AI MCP:在 Spring 里把 AI 接上你的业务系统
java·开发语言·人工智能·后端·测试工具·spring