坑爹的atoi

很多时候, 会将数据压缩存储, 这时候需要把数字存储到字符串当中

而分割后还原的atoi有个问题, 国内我发现都只是简单的告诉你这是字符串转数字的函数.....

还是老外说的明白:

int atoi( char* pStr )

write the definition for this function without using any built-in functions. if pStr is null, return 0. if pStr contains non-numeric characters, either return 0 (ok) or return the number derived so far (better) (e.g. if its “123A”, then return 123). assume all numbers are positive. plus or minus signs can be considered non-numeric characters. in order to solve this program, the programmer must understand the difference between the integer 0 and the character ‘0’, and how converting ‘0’ to an int, will not result in 0. in other words, they have to understand what ascii is all about.

意思是返回值根据不同情况都得出同一个值

.字符串为null 返回0

.字符串不是数字 返回0

.字符串是0 也返回0


所以如果你用到这个方法, 而且需要处理的话, 尽量避免0和字母混合的情况出现


实现结构很简单

int atoi( char* pStr ) 
{ 
  int iRetVal = 0; 
  int iTens = 1;
 
  if ( pStr )
  {
    char* pCur = pStr; 
    while (*pCur) 
      pCur++;
 
    pCur--;
 
    while ( pCur >= pStr && *pCur <= '9' && *pCur >= '0' ) 
    { 
      iRetVal += ((*pCur - '0') * iTens);
      pCur--; 
      iTens *= 10; 
    }
  } 
  return iRetVal; 
} 


出处:

http://www.techinterview.org/post/526339864/int-atoi-char-pstr/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值