Leetcode: atoi
来源:互联网 发布:微信一键加附近人软件 编辑:程序博客网 时间:2024/05/22 07:47
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; }};