atoi&itoa

char* itoa(int num,char*str,int radix)
{/*索引表*/
    char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    unsigned unum;/*中间变量*/
    int i=0,j,k;
    /*确定unum的值*/
    if(radix==10&&num<0)/*十进制负数*/
    {
        unum=(unsigned)-num;
        str[i++]='-';
    }
    else unum=(unsigned)num;/*其他情况*/
    /*转换*/
    do{
        str[i++]=index[unum%(unsigned)radix];
        unum/=radix;
    }while(unum);
    str[i]='\0';
    /*逆序*/
    if(str[0]=='-')
        k=1;/*十进制负数*/
    else 
        k=0;
    char temp;
    for(j=k;j<=(i-1)/2;j++)
    {
        temp=str[j];
        str[j]=str[i-1+k-j];
        str[i-1+k-j]=temp;
    }
    return str;
}

 

class Solution {
public:

    bool isdigit(char c){
        if (c >= 48 && c <= 57)
            return true;
        else
            return false;
    }
    int atoi(string str){
        long long  ans = 0,res=1;
        bool flag = false;
        char c;
        for(int i=0;i < str.size() ;i++){
            c = str[i];
            if(!flag && (c==' ' || c=='\t' || c=='\r' || c=='\n') ) continue;
            if(!flag && (c=='+' || c=='-') ){
                if(c=='-') res = -1;
                flag = true;
                continue;
            }
            if(!flag && isdigit(c)){
                flag = true;
            }
            if(!isdigit(c)) break;
            ans = ans * 10 + (c-'0');
            //cout<<ans<<' '<<c<<endl;
            if(ans > INT_MAX ){
                break;
            }
        }
        ans *= res;
        if(ans > INT_MAX) ans = INT_MAX;
        else if (ans < INT_MIN ) ans = INT_MIN;
        return (int)ans;
    }
};

 

posted on 2015-08-29 11:36  月下之风  阅读(290)  评论(0编辑  收藏  举报

导航