题目描述:
输入一个由数字组成的字符串,请把它转化成整数并输出.eg:输入字符串“123”,输出123
1分代码:
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<string.h>
-
int fun(int a,int b)
-
{
-
if (b == 0) return 1;
-
else
-
return a*fun(a,b-1);
-
}
-
int strToInt(char *str)
-
{
-
if (str == NULL)
-
return -1;
-
int i = 0,j = 0;
-
int result = 0;
-
int length = strlen(str);
-
for (i = length-1;i>=0;i--)
-
{
-
int c = str[i] - '0';//刚开始还忽略了这一步
-
result += c*fun(10,length-i-1);
-
printf("result = %d\n",result);
-
-
-
-
}
-
return result;
-
}
-
int main()
-
{
-
char str[1024];
-
gets(str);
-
int result = strToInt(str);
-
printf("转化的整数是%d\n",result);
-
return 0;
-
}
3‘程序:
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<string.h>
-
/*int fun(int a,int b)
-
{
-
if (b == 0) return 1;
-
else
-
return a*fun(a,b-1);
-
}*/
-
int strToInt(char *str)
-
{
-
if (str == NULL)
-
return -1;
-
int i = 0,j = 0;
-
int result = 0;
-
int length = strlen(str);
-
for (i = 0;str[i] != 0;i++)
-
{
-
int c = str[i] - '0';
-
result = result * 10+c;
-
}
-
return result;
-
}
-
int main()
-
{
-
char str[1024];
-
gets(str);
-
int result = strToInt(str);
-
printf("转化的整数是%d\n",result);
-
return 0;
-
}
10’程序:(处理溢出(最难的部分),空格,符号(‘+’,‘-’),空)
-
int strToInt(const char *str)
-
{
-
static const int MAX_INT = (int)((unsigned)~0 >> 1);//~的优先级高于>>
-
static const int MIN_INT = -(int)((unsigned)~0 >> 1);//
-
unsigned int n = 0;
-
if ( str == NULL)
-
{
-
return 0;
-
}
-
if (isspace(*str))//空格
-
{
-
++str;
-
}
-
int sign = 1;
-
if (*str == '-')
-
{
-
sign = -1;
-
++str;
-
}
-
char c;
-
while (isdigit(*str))
-
{
-
c = *str - '0';
-
if (sign > 0 && (n > MAX_INT/10 || (n == MAX_INT/10 && c > MAX_INT%10)))
-
{
-
n = MAX_INT;
-
break;
-
}
-
if (sign < 0 && (n > (unsigned)MIN_INT/10 || (n == (unsigned)MIN_INT/10 && c > (unsigned)MIN_INT %10)))//这里 (unsigned)的使用
-
{
-
n = MIN_INT;
-
break;
-
}
-
n = n*10+c;
-
++str;
-
}
-
return sign > 0?n:-n;
-
}
阅读(662) | 评论(0) | 转发(0) |