码迷,mamicode.com
首页 > 其他好文 > 详细

atoi()函数的实现

时间:2018-12-02 00:39:29      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:ica   necessary   enum   main   nstat   over   代码   lag   ati   

linux c库函数实现
/***
*long atol(char *nptr) - Convert string to long
*
*Purpose:
*       Converts ASCII string pointed to by nptr to binary.
*       Overflow is not detected.
*
*Entry:
*       nptr = ptr to string to convert
*
*Exit:
*       return long int value of the string
*
*Exceptions:
*       None - overflow is not detected.
*
*******************************************************************************/

long __cdecl atol(
        const char *nptr
        )
{
        int c;              /* current char */
        long total;         /* current total */
        int sign;           /* if ‘-‘, then negative, otherwise positive */

        /* skip whitespace */
        while ( isspace((int)(unsigned char)*nptr) )
            ++nptr;

        c = (int)(unsigned char)*nptr++;
        sign = c;           /* save sign indication */
        if (c == ‘-‘ || c == ‘+‘)
            c = (int)(unsigned char)*nptr++;    /* skip sign */

        total = 0;

        while (isdigit(c)) {
            total = 10 * total + (c - ‘0‘);     /* accumulate digit */
            c = (int)(unsigned char)*nptr++;    /* get next char */
        }

        if (sign == ‘-‘)
            return -total;
        else
            return total;   /* return result, negated if necessary */
}

/***
*int atoi(char *nptr) - Convert string to long
*
*Purpose:
*       Converts ASCII string pointed to by nptr to binary.
*       Overflow is not detected.  Because of this, we can just use
*       atol().
*
*Entry:
*       nptr = ptr to string to convert
*
*Exit:
*       return int value of the string
*
*Exceptions:
*       None - overflow is not detected.
*
*******************************************************************************/

int __cdecl atoi(
        const char *nptr
        )
{
        return (int)atol(nptr);
}

剑指offer实现

// StringToInt.cpp : Defines the entry point for the console application.
//

// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

long long StrToIntCore(const char* str, bool minus);

enum Status {kValid = 0, kInvalid};
int g_nStatus = kValid;

int StrToInt(const char* str)
{
    g_nStatus = kInvalid;
    long long num = 0;

    if(str != NULL && *str != ‘\0‘) 
    {
        bool minus = false;
        if(*str == ‘+‘)
            str ++;
        else if(*str == ‘-‘) 
        {
            str ++;
            minus = true;
        }

        if(*str != ‘\0‘) 
        {
            num = StrToIntCore(str, minus);
        }
    }

    return (int)num;
}

long long StrToIntCore(const char* digit, bool minus)
{
    long long num = 0;

    while(*digit != ‘\0‘) 
    {
        if(*digit >= ‘0‘ && *digit <= ‘9‘) 
        {
            int flag = minus ? -1 : 1;
            num = num * 10 + flag * (*digit - ‘0‘);

            if((!minus && num > 0x7FFFFFFF) 
                || (minus && num < (signed int)0x80000000))
            {
                num = 0;
                break;
            }

            digit++;
        }
        else 
        {
            num = 0;
            break;
        }
    }

    if(*digit == ‘\0‘) 
    {
        g_nStatus = kValid;
    }

    return num;
}

// ====================测试代码====================
void Test(char* string)
{
    int result = StrToInt(string);
    if(result == 0 && g_nStatus == kInvalid)
        printf("the input %s is invalid.\n", string);
    else
        printf("number for %s is: %d.\n", string, result);
}

int _tmain(int argc, _TCHAR* argv[])
{
    Test(NULL);

    Test("");

    Test("123");

    Test("+123");

    Test("-123");

    Test("1a33");

    Test("+0");

    Test("-0");

    //有效的最大正整数, 0x7FFFFFFF
    Test("+2147483647");    

    Test("-2147483647");

    Test("+2147483648");

    //有效的最小负整数, 0x80000000
    Test("-2147483648");    

    Test("+2147483649");

    Test("-2147483649");

    Test("+");

    Test("-");

    return 0;
}

综合库函数及剑指offer,写出如下程序

typedef enum {VALID, INVALID} ResType;  //返回的结果类型
ResType g_rtRes = VALID;

bool isdigit(char ch)
{
  return ‘0‘<=ch && ch<=‘9‘;
}

int StrToInt(const char *str)
{
  unsigned int iCur, iMax;
  int sign;
  const char *p;  

  //判断参数是否合法
  if(!str || strlen(str)<=0){
    g_rtRes = INVALID;
    return 0;
  }

  //去掉前面空格
  for(p=str; ‘ ‘==*p; p++);

  //判断正负号
  sign = 1;
  iMax = ~(1<<8*sizeof(int)-1);  //最大正整数  
  if(‘+‘==*p){
    p++;
  }else if(‘-‘ == *p){
    p++;
    sign = -1;
    iMax = ~iMax;  // sign*iMax 就是最小负正数
  }

  //首位不是数字,输入非法
  if(!isdigit(*p)){
    g_rtRes = INVALID;
    return 0;
  }

  //首位是0,特殊处理
  if(‘0‘==*p){
    if(isdigit(*(p+1))){
      g_rtRes = INVALID;      
    }
    return 0;
  }

  //累和
  for(iCur=0; isdigit(*p) && iCur<=iMax; p++){
    iCur = iCur*10 + (*p - ‘0‘);
  }

  //返回结果
  if(iCur <= iMax){
    return (int)(sign*iCur);
  }else{
    g_rtRes = INVALID;
    return 0;
  }
}// StrToInt

参考文章:
https://www.yuque.com/docs/share/32a17c69-d909-4f86-977c-e4c8c9dd51ed

atoi()函数的实现

标签:ica   necessary   enum   main   nstat   over   代码   lag   ati   

原文地址:http://blog.51cto.com/4754569/2324675

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!