字符串转成整型(int)

本文介绍了一个将字符串转换为整数(atoi)的实现方法。该方法首先去除字符串前的空白字符,接着处理正负号,并逐一读取数字字符进行数值计算。遇到非数字字符时停止计算,若结果超出整数范围,则返回边界值。

1 题目

Implement atoito convert a string to an integer.

Hint: Carefullyconsider all possible input cases. If you want a challenge, please do not seebelow and ask yourself what are the possible input cases.

Notes: It isintended for this problem to be specified vaguely (ie, no given input specs).You are responsible to gather all the input  requirements up front.

Requirements for atoi:

The functionfirst discards as many whitespace characters as necessary until the firstnon-whitespace character is found. Then, starting from this character, takes anoptional initial plus or minus sign followed by as many numerical digits aspossible, and interprets them as a numerical value.

The string cancontain additional characters after those that form the integral number, whichare ignored and have no effect on the behavior of this function.

If the firstsequence of non-whitespace characters in str is not a valid integral number, orif no such sequence exists because either str is empty or it contains onlywhitespace characters, no conversion is performed.

If no validconversion could be performed, a zero value is returned. If the correct valueis out of the range of representable values, INT_MAX (2147483647) or INT_MIN(-2147483648) is returned.

2 分析

(1) 空字符串返回0;

(2) 去除字符串前边的0;

(3) 若遇到非数字字符则终止计算;

(4) 若求出的数越界则返回最大值或者最小值。

3 实现

int atoi(string str)
{
	int start = str.find_first_not_of(' ');
	if (start > 0)
	{
		str = str.substr(start);
	}
	int size = str.size();
	if (0 == size)
	{
		return 0;
	}

	int signal = 1;
	int i = 0;
	if (str[i] == '+')
	{
		++i;
	}
	else if (str[i] == '-')
	{
		signal = -1;
		++i;
	}

	long long res = 0;
	while (i < size)
	{
		if (str[i] < '0' || str[i] > '9')
		{
			break;
		}
		res = res * 10 + (str[i] - '0');
		if (res > INT_MAX)
		{
			return signal == 1 ? INT_MAX : INT_MIN;
		}
		++i;
	}

	return res * signal;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值