8. String to Integer (atoi)

来源:互联网 发布:mtv合成机软件下载 编辑:程序博客网 时间:2024/06/06 00:36

这道题要把字符串转换成整数,这道题有点繁琐吧,要考虑前面的空格,还有加减号,还有转换的时候超出int的范围,其他的没什么。

#include<stdio.h>#include<ctype.h>int myAtoi(char* str) {    int i,temp=0,j=0;    while(str[j]==' ')        j++;    if(!isdigit(str[j])&&!isdigit(str[j+1]))        return 0;    else if('-'==str[j])    {        for(i=j+1;str[i];i++)        {            if(!isdigit(str[i]))                break;            if(temp>214748364||(temp==214748364&&str[i]>'8'))            {                temp=2147483648;                break;            }            temp=temp*10+str[i]-'0';        }        temp=-temp;    }    else if('+'==str[j])    {        for(i=j+1;str[i];i++)        {            if(!isdigit(str[i]))                break;            if(temp>214748364||(temp==214748364&&str[i]>'7'))            {                temp=2147483647;                break;            }            temp=temp*10+str[i]-'0';        }    }    else    {        for(i=j;str[i];i++)        {            if(!isdigit(str[i]))                break;            if(temp>214748364||(temp==214748364&&str[i]>'7'))            {                temp=2147483647;                break;            }            temp=temp*10+str[i]-'0';        }    }    return temp;}main(){    char s[10];    scanf("%s",s);    printf("%d\n",myAtoi(s));}

简化版:

class Solution {public:    int myAtoi(string str)     {        int i=0;        double temp=0;        int flag=1;        while(str[i]==' ')            i++;        if(!isdigit(str[i])&&!isdigit(str[i+1]))            return 0;        if(str[i] == '-' || str[i] == '+')            flag = (str[i++] == '-')? -1 : 1;        for(;str[i];i++)        {            if(!isdigit(str[i]))                break;            temp=temp*10+str[i]-'0';        }        temp=flag*temp;        if(temp>INT_MAX)            temp=INT_MAX;        if(temp<INT_MIN)            temp=INT_MIN;        return temp;    }};
0 0
原创粉丝点击