c - 递归函数计算数字字符串的后继
问题描述
解决方案
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.
推荐阅读
- python - 并行处理数千个文件
- javascript - 带有 @fingerprintjs/fingerprintjs 的角 ssr
- javascript - 使用 javascript 创建元素,可以通过循环将其放入 HTML 元素中
- reactjs - 如何
- python - FastAPI Alembic - migrations files are not being created even though output says so. Folder "versions" is empty, and tables are missing from database
- javascript - GTM custom javascript is not working, what to do?
- python - How can you edit multiple legend boxes in a seanborn scatter plot?
- github - 拉码时个人访问令牌未验证失败
- postgresql - postgres中带有链中参数的递归查询
- javascript - 在 React 中将签名图像添加到 pdf