首页 > 解决方案 > 递归函数计算数字字符串的后继

问题描述

标签: calgorithmrecursion

解决方案


A key problem is this logic:

(int(*ch))*10+successor(ch+1)

the multiplication by 10 is insufficient for larger numbers. We need to multiply by a power of 10 and we already calculated that power but didn't hang onto it:

strlen (ch)

or more specifically:

strlen(ch) - 1

A complete solution:

#include <math.h>
#include <stdio.h>
#include <string.h>

#define digit(c) (c - '0')

int successor(char *string)
{
    size_t power = strlen(string) - 1;

    if (power == 0)
    {
        return digit(*string) + 1;
    }

    return digit(*string) * pow(10, power) + successor(string + 1);
}

int main() {
    printf("%d\n", successor("2999"));

    return 0;
}

OUTPUT

> ./a.out
3000
>

TODO

What happens if successor() is passed an empty string:

printf("%d\n", successor(""));

How can you modify the code to fix this? First decide what the function should return in this situation. What happens if successor() is passed a string that represents a number too large to be contained in an int:

printf("%d\n", successor("8589934592"));

How can you modify the code to fix this? Again, first decide what the function should return in this situation.


推荐阅读