#include <limits.h>
#include <ctype.h>
#include <iostream>
class Solution {
public:
int myAtoi(string str) {
int pos;
bool negative;
if (false == get_digital(str, pos, negative)) {
return 0;
}
int res = 0;
char digital_array[MAX_SIZE] = "";
if (false == check_validity(str, pos, negative, digital_array, res)) {
return res;
}
compute_res(negative, digital_array, res);
return res;
}
private:
bool get_digital(const std::string &str, int &pos, bool &negative) {
pos = 0;
negative = false;
char ch = 0;
bool zero = false;
for (;(ch = str[pos]);pos++) {
if (' ' == ch) {
if (true == zero) {
return false;
}
continue;
}
if (!isdigit(ch) && ('+' != ch) && ('-' != ch)) {
return false;
}
if ('0' == ch) {
zero = true;
continue;
}
if (isdigit(ch)) {
return true;
}
if (true == zero) {
return false;
}
negative = ('-' == ch);
pos++;
return true;
}
return true;
}
bool check_validity(const std::string &str, int pos, bool negative, char *digital_array, int &res) {
static char INT_MAX_ARRAY[MAX_SIZE] = "2147483648";
static const int NUM_MAX_SIZE = 10;
char ch = 0;
int i = 0;
for (;(ch = str[pos]);pos++) {
if ('0' != ch) {
break;
}
}
while ((ch = str[pos]) && isdigit(ch) && i < MAX_SIZE) {
digital_array[i++] = ch;
pos++;
}
if (i > NUM_MAX_SIZE || (NUM_MAX_SIZE == strlen(digital_array) && strcmp(digital_array, INT_MAX_ARRAY) >= 0)) {
if (true == negative) {
res = INT_MIN;
return false;
}
res = INT_MAX;
return false;
}
return true;
}
void compute_res(bool negative, const char *digital_array, int &res) {
int sum = 0;
int i = 0;
char ch = 0;
while (ch = digital_array[i]) {
sum = (sum << 1) + (sum << 3) + (ch - '0');
i++;
}
if (true == negative) {
res = -sum;
return;
}
res = sum;
}
private:
const static size_t MAX_SIZE = 16;
};
