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;
}
相关推荐
共享家952719 小时前
经典动态规划题解
算法·leetcode·动态规划
起个昵称吧19 小时前
立即数、栈、汇编与C函数的调用
c语言·开发语言·汇编
1白天的黑夜120 小时前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
cellurw21 小时前
俄罗斯方块终端游戏实现 —— C语言系统编程与终端控制
c语言·算法
青草地溪水旁21 小时前
C/C++ 标准库中的 `strspn` 函数
c语言·c++
Starshime1 天前
【C语言】变量和常量
c语言·开发语言
晨非辰1 天前
#C语言——刷题攻略:牛客编程入门训练(十):攻克 循环控制(二),轻松拿捏!
c语言·开发语言·经验分享·学习·visual studio
Swift社区1 天前
LeetCode 378 - 有序矩阵中第 K 小的元素
算法·leetcode·矩阵
墨染点香1 天前
LeetCode 刷题【73. 矩阵置零】
算法·leetcode·矩阵