算法之atoi && itoa

本文介绍了如何通过自定义函数实现字符串与整数之间的转换,包括处理正负号、溢出检测等细节,并提供了一个考虑周全的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现字符串和整数互转的两个函数void itoa(int i, char *buf) 和 int atoi(char *str);

//这个函数必须考虑到32位整数的溢出问题,MAX表示的是最大值2147483647的16进制表示,MIN表示的是最小负值-2147483648的16进制表示
#define MAX ((int)0x7FFFFFFF)
#define MIN ((int)0x80000000)

int myatoi(const char * str)
{
     bool negative=false;
     unsigned long result=0;

     if(str==NULL)
         return 0;
     while(*str==' ')
         str++;
     if(*str=='-')
     {
         negative=true;
         str++;
     }
     else if(*str=='+')
         str++;
     if(*str<'0'||*str>'9')
         return 0;

     while(*str>='0' && *str<='9')
     {
         result=result*10+*str-'0';
         if((negative && result>MAX + 1) || (!negative && result>MAX))
         {
 	     //溢出检测
             return 0;
         }
 
         str++;
     }
     //负数处理
     if(negative)
         result *= -1;
     return (int)result;
 }
//因为负数的最小值无法按照先转变为整数(溢出)才转变为字符串的方式,所以直接硬编码为字符串即可
int my_itoa(int val, char* buf)
{
    const unsigned int radix = 10;

    char* p;
    unsigned int a;        //every digit
    int len;
    char* b;            //start of the digit char
    char temp;
    unsigned int u;

    p = buf;

    if (val < 0)
    {
	if(val == 0x80000000)
	{
	    char *p = "-2147483648";
	    for(i=0;i<12;i++)
	    {
		buf[i] = *p++;
   	    }
	    return 11;
	}
        *p++ = '-';
        val = 0 - val;
    }
    u = (unsigned int)val;

    b = p;

    do
    {
        a = u % radix;
        u /= radix;

        *p++ = a + '0';

    } while (u > 0);

    len = (int)(p - buf);

    *p-- = 0;

    //swap
    do
    {
        temp = *p;
        *p = *b;
        *b = temp;
        --p;
        ++b;

    } while (b < p);

    return len;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值