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;
}
相关推荐
Tisfy4 小时前
LeetCode 3240.最少翻转次数使二进制矩阵回文 II:分类讨论
算法·leetcode·矩阵·题解·回文·分类讨论
Tisfy5 小时前
LeetCode 3244.新增道路查询后的最短距离 II:贪心(跃迁合并)-9行py(O(n))
算法·leetcode·题解·贪心·思维
小杨 学习日志5 小时前
C高级学习笔记
c语言·笔记·学习
Peter_chq7 小时前
【计算机网络】HTTP协议
linux·c语言·开发语言·网络·c++·后端·网络协议
xxxmmc7 小时前
Leetcode 3355 Zero Array Transformation
算法·leetcode·差分
程序garbage8 小时前
搜索插入位置-力扣
数据结构·算法·leetcode
来知晓8 小时前
Python世界:力扣题解875,珂珂爱吃香蕉,中等
linux·python·leetcode
xiaoshiguang38 小时前
LeetCode 209 长度最小的子数组(滑动窗口)
java·算法·leetcode
m0_675988238 小时前
Leetcode3244:新增道路查询后的最短距离 II(C++)
c++·算法·leetcode