atoi 和 itoa

#include
#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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章