[leetcode] atoi

  
  
  
  

第一篇博客,看看可不可以用啦~~

 

 

  
  
  
  
  1. class Solution { 
  2. public
  3.     int atoi(const char *str) { 
  4.         // Start typing your C/C++ solution below 
  5.         // DO NOT write int main() function 
  6.         const char *p = str; 
  7.          
  8.         int ret = 0; 
  9.          
  10.         bool isPos = 1; 
  11.          
  12.         while(*p == ' ') p++; 
  13.          
  14.         if(*p == '+'){ 
  15.             isPos = 1; 
  16.             p++; 
  17.         }else if(* p == '-'){ 
  18.             isPos = 0; 
  19.             p++; 
  20.         } 
  21.          
  22.         while(*p){ 
  23.             if(*p >= '0' && *p <= '9'){ 
  24.                 if(ret > INT_MAX /10 || INT_MAX - ret*10 < *p - '0'){ 
  25.                     if(isPos) return INT_MAX; 
  26.                     else return INT_MIN; 
  27.                 } 
  28.                 ret = ret * 10 + *p - '0'
  29.                  
  30.             }else
  31.                 if(isPos) return ret; 
  32.                 else return -ret; 
  33.             } 
  34.              
  35.             p++; 
  36.         } 
  37.          
  38.         //if(ret == INT_MAX || ret == INT_MIN) return -ret; 
  39.          
  40.         if(isPos) return ret; 
  41.         return -ret; 
  42.          
  43.     } 
  44. }; 

 

你可能感兴趣的:(LeetCode)