问题描述
- 从键盘输入一个字符如(“12345”只有0-9)用递归算法将字符串转换为数字,
-
完整题目:从键盘输入一个字符如(“12345”只有0-9)用递归算法将字符串转换为数字,求算法复杂性,并验证排序正确性
解决方案
不好意思,之前发的那个没验证发现有点问题,误导了,这个验证了一下没问题。你的题目总没有说明翻译成几进制,所以我就按原样翻译了
例如字符"1234",翻译为数字1234.
void GetNumFromString(char *c,unsigned long *num);
void _tmain(int argc, _TCHAR* argv[])
{
unsigned long x;
char *pp = "1234";
x = 0;
GetNumFromString(pp,(unsigned long *)&x);
pp = "8234";
x = 0;
GetNumFromString(pp,(unsigned long *)&x);
while(1)
{
}
}
void GetNumFromString(char *c,unsigned long *num)
{
if(*c != '')
{
*num *= 10;
if(*c >= '0' && *c <= '9')
*num += *c - '0';
GetNumFromString(++c,num);
}
}
解决方案二:
unsigned long GetNumFromString(char *c)
{
static unsigned long num = 0;
if(*c == '')
return num;
num *= 10;
if(*c >= '0' && *c <= '9')
num += *c - '0';
GetNumFromString(++c);
return num;
}
时间: 2024-09-04 08:37:54