3/30/2014

Leetcode -- String to Integer (atoi)

Solution 03/30/2014
 class Solution {  
 public:  
   int atoi(const char *str) {  
     if(!*str) {  
       return 0;  
     }  
     while(*str && *str == ' ') {  
       str++;  
     }  
     bool sign = true;  
     if(*str == '+') {  
       str++;  
     } else if (*str == '-') {  
       sign = false;  
       str++;  
     }  
     if(!*str || !(*str >= '0' && *str <='9')) {  
       return 0;  
     }  
     long long number = 0;  // will fail if you do not use long long!
     while(*str) {  
       if(*str >= '0' && *str <='9') {  
         int num = *str - '0';  
         number = 10 * number + num;  
       } else {  
         break;  
       }  
       str++;  
     }  
     number = sign ? number : -number;  
     if(number >= INT_MAX) {  
       return INT_MAX;  
     } else if (number <= INT_MIN) {  
       return INT_MIN;  
     } else {  
       return (int)number;  
     }  
   }  
 };  

No comments: