从键盘输入一个字符如(“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 != '\0')
{
*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 == '\0')
return num;
num *= 10;
if(*c >= '0' && *c <= '9')
num += *c - '0';
GetNumFromString(++c);
return num;
}