力扣8
// leetcode.cpp : This file contains the 'main' function. Program execution begins and ends there.//#include "pch.h"#include<vector>#include<string>#include<iostream>using n...
·


// 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;
}
};
更多推荐



所有评论(0)