leetcode中字符串转化为数字

8. String to Integer (atoi


Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.



fas




大概就是说,我们在字符串的前面可以加入空格,和数字的符号+-,然后数字中间不能有其它字符,代码如下

int myAtoi(char* str) {
   if(*str==NULL)
   return 0;
   int res=0;
   int sign=1;
   int i=0;
  while(isspace(*str)) str++;
   if(str[0]=='-'){
       sign=-1;
       i++;
   }
   else if(str[0]=='+'){
       sign=+1;
       i++;
   }else{
       sign=+1;
   }
   while(str[i]>='0'&&str[i]<='9'){
       if(res>INT_MAX/10||(res==INT_MAX/10&&str[i]-'0'>7)){
           if(sign==1) return INT_MAX;
           else return INT_MIN;
       }
       res=10*res+(str[i++]-'0');
   }
   return sign*res;
    
}


你可能感兴趣的:(acm)