在这里插入图片描述
在这里插入图片描述

// leetcode.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include<vector>
#include<string>
#include<iostream>
using namespace std;
#include<algorithm>


class Solution {
public:
	int myAtoi(string str)

	{
		unsigned long len = str.size();//这里用unsigned long会比int好一点
		int index = 0;
		while (index < len)
		{
			if (str[index] != ' ')
			{
				break;
			}
			index++;
		}
		if (index == len)
		{
			return 0;
		}
		int sign = 1;//处理第一个正负号
		if(str[index]=='+')
		{
			index++;
		}
		else {
			sign = -1;
			index++;
		}

		//开始转换数字直到不是数字的字符
		int res = 0;
		while (index < len)
		{
			char curChar = str[index];
			if (curChar<'0' || curChar>'9')
			{
				break;
			}
			if (res > INT_MAX / 10 || (res == INT_MAX / 10 && (curChar - '0') > INT_MAX % 10))
			{
				return INT_MAX;
			}
			if (res < INT_MIN / 10 || (res == INT_MIN / 10 && (curChar - '0') > INT_MIN % 10))//当res == Integer.MAX_VALUE时,res = res * 10 + sign * (curChar - '0'); 有两种可能性:一种是加上当前数字不会超过,一种是会超过。
			{
				return INT_MIN;
			}
			res = res * 10 + sign * (curChar - '0');
			index++;
		}
		return res;
	}

};

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐