[面试] 经典面试题 atoi 的实现

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
using namespace std;

long long strToIntCore(const char *str, int sign);
bool g_flag;
int sign;
int strToInt(const char *str) {
	g_flag = false;
	long long num = 0;
	if(str != NULL && *str != '\0') {
		sign = 1;
		if(*str == '+') str++;
		else if(*str == '-') {
			str++;
			sign = -1;
		}
		if(*str != '\0') {
			num = strToIntCore(str, sign);
		}
	}
	return (int)num;
}
long long strToIntCore(const char *digs, int sign) {
	long long num = 0;
	while(*digs != '\0') {
		if(*digs >= '0' && *digs <= '9') {
			num = num * 10 + (*digs - '0');
			if((sign == 1 && num > 0x7fffffff) && (sign == -1 && num < 0x80000000)) {
				num = 0;
				break;
			}
			digs++;
		}
		else {
			num = 0;
			break;
		}
	}
	if(*digs == '\0') {
		g_flag = true;
	}
	return num*sign;
}
int main() {
	return 0;
}

posted @ 2013-03-21 20:34  小尼人00  阅读(176)  评论(0编辑  收藏  举报