1. 程式人生 > >atoi()函數的實現

atoi()函數的實現

c庫函數 pac off 類型 href .cpp digi 結果類型 main

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()函數的實現