一、功能簡介
把一個字符串轉換成整數
二、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)
面試官至少會期待應聘都能夠在不需要提示的情況下,考慮到輸入的字符串中有非數字字符和正負號,要考慮到最大的正整數和最小的負整數以及溢出。同時面試試還期待應聘者能夠考慮到當輸入的字符串不能轉換成整數時,應該如何做錯誤處理。
1、檢查字符串是否為空
2、對非法輸入,返回0,並設置全局變量
3、溢出
4、空字符串""
5、輸入字符串只有"+"或"-"號
四、劍指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