class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(str==NULL)
return 0;
int i=0;
bool negative=false;
//deal with spaces at the beginning of the string
while(str[i]==' ')
++i;
//check if the number is negative
if(str[i]=='-'){
negative=true;
++i;
} else if(str[i]=='+')
++i;
//do the real thing
double result=0;
while(str[i]!='\0'&&str[i]>='0'&&str[i]<='9'){
int n=str[i]-'0';
result=result*10+n;
++i;
}
//perform dound check
int output;
if(negative)
output=result>INT_MAX?INT_MIN:(~(unsigned int)result+1);
else output=result>=INT_MAX?INT_MAX:result;
return output;
}
};
Leetcode: atoi
最新推荐文章于 2024-06-16 22:09:39 发布