C语言 | Leetcode C语言题解之第564题寻找最近的回文数

题目:

题解:

cpp 复制代码
#define MAX_STR_LEN 32
typedef unsigned long long ULL;

void reverseStr(char * str) {
    int n = strlen(str);
    for (int l = 0, r = n-1; l < r; l++, r--) {
        char c = str[l];
        str[l] = str[r];
        str[r] = c;
    }
}

ULL * getCandidates(const char * n, int * returnSize) {
    int len = strlen(n);
    int pos = 0;
    ULL * candidates = (ULL *)malloc(sizeof(ULL) * 5);
    candidates[pos++] = (ULL)pow(10, len) + 1;
    candidates[pos++] = (ULL)pow(10, len - 1) - 1;
    char str[MAX_STR_LEN], prefix[MAX_STR_LEN];
    char candidate[MAX_STR_LEN];
    snprintf(str, (len + 1) / 2 + 1, "%s", n);
    ULL selfPrefix = atol(str);    
    for (ULL i = selfPrefix - 1; i <= selfPrefix + 1; i++) {
        sprintf(prefix, "%ld", i);
        sprintf(candidate, "%s", prefix);
        reverseStr(prefix);
        sprintf(candidate + strlen(candidate), "%s", prefix + (len & 1));
        candidates[pos++] = atoll(candidate);
    }
    *returnSize = pos;
    return candidates;
}

char * nearestPalindromic(char * n){
    ULL selfNumber = atoll(n), ans = -1;
    int candidatesSize = 0;
    const ULL * candidates = getCandidates(n, &candidatesSize);
    for (int i = 0; i < candidatesSize; i++) {
        if (candidates[i] != selfNumber) {
            if (ans == -1 ||
                labs(candidates[i] - selfNumber) < labs(ans - selfNumber) ||
                labs(candidates[i] - selfNumber) == labs(ans - selfNumber) && candidates[i] < ans) {
                ans = candidates[i];
            }
        }
    }
    char * str = (char *)malloc(sizeof(char) * MAX_STR_LEN);
    sprintf(str, "%ld", ans);
    free(candidates);
    return str;
}
相关推荐
神圣的大喵7 小时前
平台无关的嵌入式通用按键管理器
c语言·单片机·嵌入式硬件·嵌入式·按键库
喵了meme9 小时前
C语言实战2
c语言·开发语言·网络
网易独家音乐人Mike Zhou10 小时前
【嵌入式模块芯片开发】LP87524电源PMIC芯片配置流程,给雷达供电的延时上电时序及API函数
c语言·stm32·单片机·51单片机·嵌入式·电源·毫米波雷达
自学小白菜10 小时前
每周刷题 - 第三周 - 双指针专题 - 02
python·算法·leetcode
小立爱学习10 小时前
ARM64 指令 --- CASP / CASPA / CASPL / CASPAL
linux·c语言
不能只会打代码11 小时前
力扣--3433. 统计用户被提及情况
java·算法·leetcode·力扣
武汉唯众智创11 小时前
职业院校C语言程序设计(AIGC版)课程教学解决方案
c语言·开发语言·aigc·程序设计·c语言程序设计·c语言程序设计实训室
qq_4017004111 小时前
C语言void*
c语言·开发语言
程芯带你刷C语言简单算法题12 小时前
Day28~实现strlen、strcpy、strncpy、strcat、strncat
c语言·c++·算法·c