String to Integer (atoi)
int atoi(const char *str) {
// Note: The Solution object is instantiated only once and is reused by each test case.
//skip whitespace
const char* p = str;
while(*p==' ')
++p;
if(*p!='+'&&*p!='-'&&!isdigit(*p))
return 0;
bool bNegative = false;
if(*p=='+')
p++;
else if(*p=='-')
{
bNegative = true;
p++;
}
long long sum = 0;
while(*p&&isdigit(*p))
{
sum = sum*10+(*p-'0');
if(sum>=(long long)INT_MAX+1)
return (bNegative?INT_MIN:INT_MAX);
p++;
}
return (bNegative?-sum:sum);
}
浙公网安备 33010602011771号