Sunday, 17 July 2016

String to Integer (atoi)

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases.
Notes: It is intended for this problem to be specified vaguely (i.e., no given input specs). You are responsible to gather all the input requirements up front.
 class Solution {  
 public:  
   string trim(string str, int *len){  
     int j = 0, i = 0;  
     int first = 0;  
     while(str[i] != '\0'){  
       if(str[i] != ' ' && !first){  
         str[j++] = str[i];  
       }  
       if(j > 0 && str[i] == ' '){  
         break;  
       }  
       i++;  
     }  
     *len = j;  
     return str;  
   }  
   int myAtoi(string str) {  
     int len = str.length();  
     if(len == 0){  
       return 0;  
     }  
     string temp = trim(str, &len);  
     temp[len] = '\0';  
     int sign = 1;  
     if(temp[0] == '+'){  
       sign = 1;  
     }else if(temp[0] == '-'){  
       sign = -1;  
     }  
     int i;  
     if(temp[0] == '+' || temp[0] == '-'){  
       i = 1;  
     }else{  
       i = 0;  
     }  
     long long int result = 0;  
     while(i < len){  
       if(temp[i] == ' ' || temp[i] - '0' < 0 || temp[i] - '0' > 9){  
         return result * sign;  
       }  
       result = result * 10 + (temp[i] - '0');  
       if(result * sign > INT_MAX){  
         return INT_MAX;  
       }  
       if(result * sign < INT_MIN){  
         return INT_MIN;  
       }  
       i++;  
     }  
     return (int)result * sign;  
   }  
 };  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive