天天看点

atoi 和 itoa

#include <stdio.h>

#include <stdlib.h>

#include <assert.h>

int atoi(const char *str)

{

        int sign = 1;

        int total = 0;

        assert(str!=NULL);

        while(*str==' ')

        {

                str++;

        }

        if(*str=='-')

        {

                sign = -1;

                str++;

        }

        else if(*str=='+')

        {

                str++;

        }

        while(*str)

        {

                int temp = *str - '0';

                assert(temp<=9&&temp>=0);

                total = total*10 + temp;

                str++;

        }

        return total*sign;

}

char *itoa(int num,char *str)

{

        char *start = str;

        char *temp = str;

        int negative = 0;

        assert(str!=NULL);

        if(num<0)

        {

                num*=-1;

                negative = 1;

        }

        do

        {

                *str = num%10 + '0',

                num = num/10;

                str++;

        }while(num>0);

        if(negative == 1)

        {

                *str++ = '-';

                *str = '\0';

        }

        else

        {

                *str = '\0';

        }

        str--;

        while(temp < str)

        {

                *temp=*temp^*str;

                *str=*temp^*str;

                *temp=*temp^*str;

                temp++;

                str--;

        }

        return start;

}