[Topic] 8. String conversion integer (atoi)——Please implement a myAtoi(string s) function to convert a string into a 32-bit signed integer (similar to the atoi function in C/C++) ).

Topic: 8. String conversion to integer (atoi)

Please implement a myAtoi(string s) function to convert a string into a 32-bit signed integer (similar to the atoi function in C/C++).

Insert picture description here

answer:

int myAtoi(char* s)
{
    
    
	long ret = 0;
    // 记录正负数
	int flag = 1;
    // 判断空格
	while (*s == ' ')
	{
    
    
		s++;
	}
    // 判断是否为正数
	if (*s == '+')
	{
    
    
		s++;
		flag = 1;
	}
    // else if防止"+-12"这种情况
    // 判断是否为负数
	else if (*s == '-')
	{
    
    
		s++;
		flag = -1;
	}
    // 开始遍历数字部分
	while (*s)
	{
    
    
        // 开始遍历数字部分
		if (isdigit(*s))
		{
    
    
			ret = ret * 10 + (*s - '0') * flag;
            // 判断是否最大值溢出
			if (ret >= INT_MAX )
			{
    
    
				ret = INT_MAX;
				break;
			}
            // 判断是否最小值溢出
            if(  ret <= INT_MIN )
            {
    
    
                ret = INT_MIN;
                break;
            }
            // 数字范围正常,继续遍历
			s++;
		}
        // 遇到非数字字符,结束遍历
        // 返回正常情况
		else
			return ret;
	}
    // 返回异常情况
	return ret;
}

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/113935922