Wednesday, August 26, 2015

Leetcode: String to Integer (atoi) (string)

PROBLEM:

https://leetcode.com/problems/string-to-integer-atoi/


---------------------------------


Basically the problem want to translate:
   "   +987778xw " 
into an integer.

Note:
1. limit check: INT_MAX, INT_MIN;
    the problem indicate the  INT_MAX (2147483647) or INT_MIN (-2147483648). the value 2147483647 is the limit of unsigned long long!! See below:

INT_MINMinimum value for an object of type int-32767 (-215+1) or less*
INT_MAXMaximum value for an object of type int32767 (215-1) or greater*
UINT_MAXMaximum value for an object of type unsigned int65535 (216-1) or greater*
LONG_MINMinimum value for an object of type long int-2147483647 (-231+1) or less*
LONG_MAXMaximum value for an object of type long int2147483647 (231-1) or greater*
ULONG_MAXMaximum value for an object of type unsigned long int4294967295 (232-1) or greater*


This confused me. 

2. 



//////////////////////////////////////////////////////
//code 12ms

class Solution {
public:
       int myAtoi(string str) {
              //pass the initial space
              int i = 0;
              unsigned long long res = 0;
              while (str[i] == ' ')i++;

              //parse the first non space char
              if (str[i] != '+' && str[i] != '-' && isdigit(str[i]) == 0)return 0;
              bool neg = false;
              if (str[i] == '+') { neg = false; i++; }
              else if (str[i] == '-') { neg = true; i++; }
              else neg = false;
              //parse the char followered by + -
              if (isdigit(str[i]) == 0)return 0;
              else {
                     while (isdigit(str[i])){
                           res = res * 10 + str[i] - '0';
                           if (res>INT_MAX)return neg ? INT_MIN : INT_MAX;
                           i++;
                     }
              }
              return neg ? -res : res;
       }
};





No comments:

Post a Comment