String to Integer (atoi) 以及 (atof)

String to Integer (atoi)

 

http://oj.leetcode.com/problems/string-to-integer-atoi/#

原题地址


//通过测试


//此题注意的事项:边界溢出,非法字符(含开头空格),带负号等
//当达到最大值: INT_MAX (2147483647) or INT_MIN (-2147483648) ---》返回!


int atoi(const char *str) {
	
	int falg = 1;
	long long num = 0;//在vc下无法通过测试,c99才行,及后面的版本


	while(*str == ' ')str++;		//当使用while(*str++ == ' ');由于当最后不成立,还++导致负号被忽略,注意!!!

	if (*str == '-')
	{
		falg = -1;
		str++;
	}
	else if (*str == '+')
	{
		falg = 1;
		str++;
	}


	while( *str)
	{
		if (*str >='0'&&*str <= '9')
		{
			num = num*10 + *str-'0';
		}
		else
		{
			break;
		}
		if (falg == -1)
		{
			if (-1*num<INT_MIN)return INT_MIN;
		}
		else
		{
			if (num>INT_MAX)return INT_MAX;
		}


		str++;
	}
	return falg*num;
}

第二次

此题需防御处理:

1.非法字符

2.正负号

3.中间空格

4.前端空格,尾部空格(遇到直接break就可以,当初非法字符!!)

5.最大整形处理,INT_MAX,INT_MIN  注意俩者分别为2147483647   -2147483648 尾部一个为7,一个为8的注意。故而可关注为8为不正常,减少代码。(一开始未处理好)
6.数字0(前面的)

正常应该有一全局变量,来存储是否输入为合法。

    int atoi(const char *str) 
    {
    	bool negative = false;
    	bool space_exit = false;
    	int num = 0;
    
    	while(*str == ' ')
    	{
    		str++;
    	}
    
    	if (*str == '+')
    	{
    		str++;
    	}
    	else if(*str == '-')
    	{
    		str++;
    		negative = true;
    	}
    
    	while(*str != '\0')
    	{
    		if(*str == ' ')
    		{
    			space_exit = true; 直接break就可以,没必要在判断是否为真!
    		}
    		else if(*str >= '0' && *str <= '9'&&!space_exit)
    		{
				if(num > INT_MAX/10 ||(num == INT_MAX/10 && *str-'0' > INT_MAX%10))
    			{
    				num = negative?INT_MIN:INT_MAX;//大于7 即*str-'0' > INT_MAX%10
    			}
    			else
    			{
    				num = num*10 + *str - '0';
    			}
    			 
    		}
    		else
    		{
    			break;
    		}
    		str++;
    	}
    	return negative?num*(-1):num;
    }
atof的实现(类似)

float atof_my(const char *str) 
{
	assert(str);
	bool negative = false;
	bool space_exit = false;
	bool dot_exit = false;

	float num_high = 0.0;
	float num_low = 0;
	float factor_low = 1;
	float num = 0.0;

	while(*str == ' ')
	{
		str++;
	}

	if (*str == '+')
	{
		str++;
	}
	else if(*str == '-')
	{
		str++;
		negative = true;
	}

	while(*str != '\0')
	{
		if(*str == '.' && !dot_exit)
		{
			dot_exit = true;
		}
		else if(*str == '.' && dot_exit)
		{
			break;
		}
		else if(*str == ' ')
		{
			space_exit = true;//直接break
		}
		else if(*str >= '0' && *str <= '9'&&!space_exit)
		{
			if(!dot_exit)
			{
				num_high = num_high*10 + *str - '0';
			}
			else
			{
				factor_low *= 0.1;
				num_low = num_low + (*str - '0')*factor_low;
			}

		}
		else
		{
			break;
		}
		str++;
	}
	
	num = num_high+num_low;

	return negative?num*(-1):num;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值