Facebook Interview Question
Software Engineer / Developersmake it num += num*10 + str[i] - '0';. for positive and negative you can use flag and make the return value positive and negative depending upon that
int atoi(char *str, int strLen){
int sign = 1;
int i = 0;
int result = 0;
if(str == NULL) return -1;
if(str[i] == '-') {
sign = -1;
i++;
}
while (i < strLen){
if(isdigit(str[i])){
checkIntOverflow(result, INT_MAX);
result = result*10 + str[i] - '0';
}else{
fprintf(stderr, "not valid integer string\n");
}
i++;
}
return result;
}
enum err_t
{
ERR_OK,
ERR_ARG,
ERR_INVAL,
ERR_OVERFLOW,
};
typedef int BOOL;
#define TRUE 1
#define FALSE 0
err_t atoi(const char *str, int *num)
{
BOOL negative = FALSE;
err_t err = ERR_OK;
unsigned int result = 0, temp;
unsigned int addition;
if (num == NULL) {
err = ERR_ARG;
goto out;
}
if (str == NULL) {
err = ERR_ARG;
goto out;
}
if (*str == '-') {
negative = TRUE;
++str;
} else if (*str == '+') {
++str;
}
while (*str) {
if (*str >= '0' && *str <= '9') {
addition = (unsigned int)(*str - '0');
if (0 != (result & (0xF0 << (8 * (sizeof(unsigned int) - 1))))) {
err = ERR_OVERFLOW;
goto out;
}
temp = result << 1; // temp = result * 2;
result <<= 3; // result *= 8;
if (temp + result < result) {
err = ERR_OVERFLOW;
goto out;
}
result = temp + result; // finally multiplied by 10, NO overflow.
if (addition + result < result) {
err = ERR_OVERFLOW;
goto out;
}
result += addition;
++str;
} else {
err = ERR_INVAL;
}
}
if (0 != (result & (1 << (8 * sizeof(unsigned int) - 1)))) {
err = ERR_OVERFLOW;
goto out;
}
*num = (int)result;
if (negative) {
*num *= -1;
}
out:
return err;
}
int Atoi(const char * ptr) {
long long rs = 0;
bool minus = false;
while (*ptr == ' ') ptr++;
if (*ptr == '-') {
minus = true;
ptr++;
} else if (*ptr == '+') ptr++;
while (*ptr >= '0' && *ptr <= '9') {
rs = rs * 10 + *ptr - '0';
ptr++;
if (rs > INT_MAX) break;
}
if (minus) rs *= -1;
if (rs > INT_MAX) return INT_MAX;
if (rs < INT_MIN) return INT_MIN;
return rs;
}
- December 14, 2010