8、请编写能直接实现 int atoi(const char * pstr)函数功能的代码

/************************************************************************/
/* 8、请编写能直接实现 int atoi(const char * pstr)函数功能的代码           */
/************************************************************************/
//考虑全局变量返回结果是否有效,和大数问题
bool isToIntValid =true;
int strToInt(const char *str)
{
	long long num = 0;
	int mark = (*str== '-' ? -1: 1);
	long long upperBound = numeric_limits<int>::max();;
	if(mark == -1)
		++upperBound;

	const char* temp = (*str == '+' || *str == '-') ? str + 1: str;
	for( ;*temp >= '0' && *temp <= '9'; ++temp)
	{
		num = num * 10 + *temp - '0';    
		if(num > upperBound)
		{
			//越界,atoi中对于越界直接取最值
			isToIntValid = false;
			num = upperBound;
			break;
		}
	}
	if(*temp !='\0' || *str == '0')
		isToIntValid = false;
	return  static_cast<int>(mark * num); 
}
void testOfstrToInt()
{
	assert(atoi("+1234") == strToInt("+1234"));
	assert(atoi("-1234") == strToInt("-1234"));
	assert(atoi("+aaa234") == strToInt("+aaa234"));
	assert(atoi("aaa1234") == strToInt("aaa1234"));
	assert(atoi("-1234a") == strToInt("-1234a"));
	assert(atoi("1234") == strToInt("1234"));
	assert(atoi("12a34") == strToInt("12a34"));
	assert(atoi("aaaa") == strToInt("aaaa"));
	assert(atoi("0123") == strToInt("0123"));
	//大数
	assert(atoi("123456789012345123456") == strToInt("123456789012345123456"));
	assert(atoi("-123456789012345123456") == strToInt("-123456789012345123456"));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值