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;
}
相关推荐
tkevinjd2 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
程序员烧烤4 小时前
【leetcode刷题007】leetcode116、117
算法·leetcode
yanqiaofanhua4 小时前
C语言自学--预处理详解
c语言·开发语言
杨福瑞5 小时前
C语言⽂件操作讲解(总)
c语言·开发语言
Swift社区7 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato7 小时前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
巴里巴气7 小时前
第15题 三数之和
数据结构·算法·leetcode
润 下7 小时前
C语言——深入解析C语言指针:从基础到实践从入门到精通(三)
c语言·开发语言·经验分享·笔记·学习·程序人生·其他
润 下8 小时前
C语言——深入解析C语言指针:从基础到实践从入门到精通(二)
c语言·开发语言·经验分享·笔记·学习·程序人生
西阳未落8 小时前
LeetCode——双指针(进阶)
c++·算法·leetcode