将字符串转换成整数

来自剑指offer

题目:把字符串转换成整数

分析:题比较简单,但是容易写完整的人不多。

g_nStatus来区分输入是否为非法字符,比如当输入空串和'0'时,通过全局变量进行区分。

代码

#include "stdafx.h"
#include <iostream>
using namespace std;
enum Status {kValid=0, kInvalid};
int g_nStatus = kValid;

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<( int)0x80000000) )
			{
				num = 0;
				break;
			}
			digit++;
		}
		else	//有非法字符情况
		{
			num = 0;
			break;
		}
	}
	if (*digit == '\0')
		g_nStatus = kValid;

	return num;
}

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;
}

int _tmain(int argc, _TCHAR* argv[])
{
	char* pStr[] ={"-999","","0","9999999"};
	int result;

	for ( int i = 0; i < 4; i++ )
	{
		result = StrToInt(pStr[i]);
		if ( g_nStatus == kValid )
			cout << result <<endl;
		else
			cout <<pStr[i] << " :为非法转换字符" <<endl;
	}
	
	return 0;
}


你可能感兴趣的:(将字符串转换成整数)